Java8新特性,List分组排序
1.分组(多字段分组)
Map<String,List<Fruit>> fruitMap = fruitList.stream().collect(Collectors.groupingBy(Fruit::getName));
Map<String, List<CalbPrOutputSum>> map = outputSums.stream().collect(Collectors.groupingBy(t -> t.getModelNum()));
Map<String, List<WorkPlanVo>> collect = value.stream().collect(Collectors.groupingBy(a -> MessageFormat.format("{0}#{1}#{2}#{3}#{4}", a.getWorkshop(),
a.getProjectCode(), a.getProdLineCode(), a.getModelCode(), a.getOutputOp())));
2.使用年龄进行升序排序
List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());
3.使用年龄进行降序排序(使用reversed()方法):
List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed()).collect(Collectors.toList());
4. 使用年龄进行降序排序,年龄相同再使用身高升序排序
List<StudentInfo> studentsSortName = studentList.stream()
.sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight))
.collect(Collectors.toList());
5.过滤
List<Employee> employees = new ArrayList<Employee>();
employees.addAll(Arrays.asList(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10));
Optional<Employee> first = employees.stream().filter(t -> "M".equals(t.getGender())).findFirst();
List<Employee> collect = employees.stream().filter(t -> "M".equals(t.getGender())).collect(Collectors.toList());
List<Employee> collect1 = employees.stream().filter(t -> "M".equals(t.getGender())).filter(t -> "Ricky".equals(t.getFirstName())).collect(Collectors.toList());
5.在使用Collectors.groupingBy分组时,如果分组的字段中有值为null,会抛出空指针异常
example:
class Stu{
String age;
String sex;
public Stu(String age, String sex) {
this.age = age;
this.sex = sex;
}
}
@Test
void test1(){
List<Stu> objects = new ArrayList<>();
objects = Arrays.asList(new Stu("18",null),new Stu("19","男"),new Stu("17","女"));
Map<String, List<Stu>> collect = objects.stream().collect(Collectors.groupingBy(x -> x.getSex()));
System.out.println(collect);
}
输出:java.lang.NullPointerException: element cannot be mapped to a null key
解决办法:
@Test
void test1(){
List<Stu> objects = new ArrayList<>();
objects = Arrays.asList(new Stu("18",null),new Stu("19","男"),new Stu("17","女"));
Map<Optional<String>, List<Stu>> collect = objects.stream().collect(Collectors.groupingBy(x -> Optional.ofNullable(x.getSex())));
System.out.println(collect);
ArrayList<Stu> finalList = new ArrayList<Stu>();
for (Map.Entry<Optional<String>, List<Stu>> optionalListEntry : collect.entrySet()) {
//Optional<String> key = optionalListEntry.getKey();
//key.isPresent()//分组的键不为空
if (optionalListEntry.getKey().isPresent()){
finalList.addAll(optionalListEntry.getValue());
}
}
System.out.println(finalList);
}
输出:
{Optional.empty=[Stu{age='18', sex='null'}], Optional[女]=[Stu{age='17', sex='女'}], Optional[男]=[Stu{age='19', sex='男'}]}
[Stu{age='17', sex='女'}, Stu{age='19', sex='男'}]