List1.2集合按照多个属性分组 1.2.1多个属性拼接出一个组合属性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}
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); List1.2.2嵌套调用groupBylist = 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; }
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); Listlist = 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; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)