首頁  >  文章  >  Java  >  java分組統計功能如何實現

java分組統計功能如何實現

王林
王林轉載
2023-04-29 08:52:061309瀏覽

大家來看看下面的案例:

//下面是初始化的数据
       List<Student> list = new ArrayList<Student>();
        Student student1 = new Student("李四1", "女", "一班");
        Student student2 = new Student("李四2", "女", "一班");
        Student student3 = new Student("李四3", "女", "一班");
        Student student4 = new Student("李四4", "男", "一班");
        Student student5 = new Student("李四5", "男", "一班");
        Student student6 = new Student("李四6", "男", "二班");
        Student student7 = new Student("李四7", "男", "二班");
        Student student8 = new Student("李四8", "男", "二班");
        Student student9 = new Student("李四9", "男", "二班");
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        list.add(student5);
        list.add(student6);
        list.add(student7);
        list.add(student8);
        list.add(student9);

1.合理利用map操作

在實際開發中合理的利用map自帶的方法,能解決很多問題

 for (Student  stu : list) {
            if (!map.containsKey(stu.getProvinceCode())) {
                ArrayList<ArrearageDeal> al = new ArrayList<ArrearageDeal>();
                map.put(stu.getProvinceCode(),  al.add(stu));
            } else {
                map.get(stu.getProvinceCode()).add(stu);
            }
        }

2.利用guava的Multimap

Multimap<String, Student> mulMap = ArrayListMultimap.create();
for (Student  stu : list) {
       mulMap.put(stu.getGrade,stu);   
}

3.使用jdk8新特性–不要排斥新東西

畢竟java14都出來了,java8的新特性還是需要多了解

//一行就可以解决
Map<String, List<Student  >> collect = list.stream().collect(Collectors.groupingBy(ArrearageDeal::getGrade));

上面三種當時從程式碼量來看,java8的最簡潔。但實際開發中結合具體場景來說2、3兩種都是不錯的選擇。

Java8 多個欄位分組統計

// 分组统计
Map<String, Long> countMap = records.stream().collect(Collectors.groupingBy(o -> o.getProductType() + "_" + o.getCountry(), Collectors.counting()));
 List<Record> countRecords = countMap.keySet().stream().map(key -> {
    String[] temp = key.split("_");
    String productType = temp[0];
    String country = temp[1];     
    Record record = new Record();
    record.set("device_type", productType);
    record.set("location", country;
    record.set("count", countMap.get(key).intValue());
    return record;
}).collect(Collectors.toList());

以上是java分組統計功能如何實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除