遍历
for (Entry<String, String> entry: map.entrySet()) { key = entry.getKey(); value = entry.getValue();}
排序
List<StudentInfo> studentList = new ArrayList<>();studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3)));studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));// 按【年龄】升序排序 (Integer类型)List<StudentInfo> studentsSortName = studentList.stream() .sorted(Comparator.comparing(StudentInfo::getAge)) .collect(Collectors.toList());//按【年龄】降序排序 (Integer类型)List<StudentInfo> studentsSortName2 = studentList.stream() .sorted(Comparator.comparing(StudentInfo::getAge).reversed()) .collect(Collectors.toList());// 先按【年龄】降序排序,再按【身高】升序排序 (Integer类型)List<StudentInfo> studentsSortName = studentList.stream() .sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight)) .collect(Collectors.toList());
分组
// 分组Map<String, List<Employee>> map = employees.stream() .collect(Collectors.groupingBy(Employee::getCity))// 分组计数Map<String, Long> map = employees.stream() .collect(Collectors.groupingBy(Employee::getCity, Collectors.counting()));// 分组求平均值Map<String, Double> map = employees.stream() .collect(Collectors.groupingBy(Employee::getCity, Collectors.averagingInt(Employee::getAge)));// 分组求和Map<String, Long> map = employees.stream() .collect(Collectors.groupingBy(Employee::getCity, Collectors.summingLong(Employee::getAmount)));// 分组-选字段输出Map<String, Set<String>> map = employees.stream().collect( Collectors.groupingBy(Employee::getCity, Collectors.mapping(Employee::getName, Collectors.toSet())));
BigDecimal 分组求和
Map<String, BigDecimal> dSumQtyMap = allDetails.stream() .collect(Collectors.toMap(Detail::getSrcDetailId, Detail::getQty, BigDecimal::add));list.stream() .map(e->e.getValue()) .reduce(BigDecimal.ZERO, BigDecimal::add);
重复元素
List<User> users = new ArrayList<>(); users.add(new User("xpf1","1238",18)); users.add(new User("xpf2","1234",18)); users.add(new User("xpf3","1235",18)); users.add(new User("xpf","1236",18)); users.add(new User("xpf","1237",18)); Map<String, Long> collect = users .stream() .map(User::getUserName) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); List<String> result = new ArrayList<>(); collect.forEach((k,v)->{ if(v>1) result.add(k); }); System.out.println(result.toString());