【Java8】stream流groupingBy常见用法。

1.1对集合按照单个属性分组、分组计数、排序

List items =  

  Arrays.asList("apple", "apple", "banana",  

  "apple", "orange", "banana", "papaya");  

// 分组  

  Map> result1 = items.stream().collect(
  Collectors.groupingBy(Function.identity()));  

//{papaya=[papaya], orange=[orange], banana=[banana, banana], apple=[apple, apple, apple]}  

  System.out.println(result1);  

// 分组计数  

  Map result2 = items.stream().collect(  

    Collectors.groupingBy(  

      Function.identity(), Collectors.counting()  

    )  

    );  

// {papaya=1, orange=1, banana=2, apple=3}  

  System.out.println(result2);  

  Map finalMap = new LinkedHashMap<>();  

//分组, 计数和排序  

  result2.entrySet().stream()  

    .sorted(Map.Entry.comparingByValue().reversed())  

    .forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));  

System.out.println(finalMap);

// {apple=3, banana=2, papaya=1, orange=1}  

1.2集合按照多个属性分组

1.2.1多个属性拼接出一个组合属性

public class Main {
    public static void main(String[] args) {
        User user1 = new User("zhangSan", "beijing", 10);
        User user2 = new User("zhangSan", "beijing", 20);
        User user3 = new User("liSi", "shanghai", 30);
        List list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        Map> collect = list.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
        System.out.println(collect);
//    {zhangSan#beijing=[User(name=zhangSan, address=beijing, age=10), User(name=zhangSan, address=beijing, age=20)],
//        liSi#shanghai=[User(name=liSi, address=shanghai, age=30)]}
    }
    private static String fetchGroupKey(User user){
        return user.getName() + "#" + user.getAddress();
    }
}
@Data
@AllArgsConstructor
class User{
    private String name;
    private String address;
    private Integer age;
}

1.2.2嵌套调用groupBy

public class Main {
    public static void main(String[] args) {
        User user1 = new User("zhangSan", "beijing", 10);
        User user2 = new User("zhangSan", "beijing", 20);
        User user3 = new User("liSi", "shanghai", 30);
        List list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        Map>> collect
                = list.stream().collect(
                Collectors.groupingBy(
                        User::getAddress, Collectors.groupingBy(User::getName)
                )
        );
        System.out.println(collect);
//   {shanghai={liSi=[User(name=liSi, address=shanghai, age=30)]},
//   beijing={zhangSan=[User(name=zhangSan, address=beijing, age=10), User(name=zhangSan, address=beijing, age=20)]}}

    }
}
@Data
@AllArgsConstructor
class User{
    private String name;
    private String address;
    private Integer age;
}

你可能感兴趣的:(Java8,流,java)