>  기사  >  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. 맵 연산의 합리적인 사용

실제 개발에서는 맵 고유의 방법을 합리적으로 사용하면 많은 문제를 해결할 수 있습니다.

 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으로 문의하시기 바랍니다. 삭제