按照多个字段对Java对象列表进行排序,并按照特定字段进行分组。
创始人
2024-08-23 20:30:13
0

以下是一个示例代码,演示了如何按照多个字段对Java对象列表进行排序,并按照特定字段进行分组。

假设有一个Person类,有name、age和city字段,我们希望按照city字段进行分组,并在每个城市的分组内按照age字段进行排序。

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SortingAndGroupingExample {

    public static void main(String[] args) {
        // 创建一个Person对象列表
        List personList = new ArrayList<>();
        personList.add(new Person("John", 25, "New York"));
        personList.add(new Person("Alice", 30, "London"));
        personList.add(new Person("Bob", 20, "New York"));
        personList.add(new Person("David", 35, "London"));
        personList.add(new Person("Eva", 40, "New York"));

        // 按照city字段进行分组,并在每个分组内按照age字段进行排序
        Map> groupedAndSortedMap = personList.stream()
                .sorted(Comparator.comparing(Person::getAge))
                .collect(Collectors.groupingBy(Person::getCity));

        // 打印结果
        groupedAndSortedMap.forEach((city, persons) -> {
            System.out.println("City: " + city);
            persons.forEach(System.out::println);
            System.out.println("------------------");
        });
    }

    static class Person {
        private String name;
        private int age;
        private String city;

        public Person(String name, int age, String city) {
            this.name = name;
            this.age = age;
            this.city = city;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

        public String getCity() {
            return city;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", city='" + city + '\'' +
                    '}';
        }
    }
}

上述代码将根据age字段对Person对象列表进行排序,并根据city字段进行分组。输出结果将按照城市进行分组,并在每个分组内按照年龄进行排序。

相关内容

热门资讯

第3分钟模板!wejoker辅... 第3分钟模板!wejoker辅助器怎么卖(透视)原来存在有辅助教程(哔哩哔哩)运wejoker辅助器...
一分钟大纲!wepoker私人... 一分钟大纲!wepoker私人局辅助(透视)总是存在有辅助工具(哔哩哔哩)1、金币登录送、破产送、升...
第八分钟窍要!德普之星有辅助软... 第八分钟窍要!德普之星有辅助软件吗(透视)切实有辅助透视(哔哩哔哩)该软件可以轻松地帮助玩家将德普之...
第4分钟手册!wepoker好... 第4分钟手册!wepoker好友房开挂(透视)竟然是有辅助安装(哔哩哔哩)wepoker好友房开挂能...
2分钟指南书!wepoker养... 2分钟指南书!wepoker养号规律(透视)真是有辅助透视(哔哩哔哩)wepoker养号规律辅助器是...
九分钟方针!wepoker俱乐... 九分钟方针!wepoker俱乐部辅助(透视)好像真的有辅助脚本(哔哩哔哩)1、起透看视 wepoke...
8分钟妙招!德州局脚本(透视)... 8分钟妙招!德州局脚本(透视)都是是真的有辅助安装(哔哩哔哩)德州局脚本辅助器是一种具有地方特色的麻...
两分钟大纲!hhpoker脚本... 两分钟大纲!hhpoker脚本下载(透视)一直真的是有辅助开挂(哔哩哔哩)1、hhpoker脚本下载...
第三分钟总结!wepoker透... 第三分钟总结!wepoker透视脚本免费下载pc(透视)竟然是有辅助安装(哔哩哔哩)1、wepoke...
8分钟操作!hhpoker怎么... 8分钟操作!hhpoker怎么防作必弊(透视)其实有辅助脚本(哔哩哔哩)1、全新机制【hhpoker...