Java8之前,使用匿名内部类的基本排序:
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student user1, Student user2) {
return user1.getX().compareTo(user2.getX());
}
});
Java8采用lamda:
//法一:根据匿名内部类修改
Collections.sort(list,(Student user1, Student user2) ->user1.getX().compareTo(user2.getX()));
//单条件
Collections.sort(list,Comparator.comparing(Student :: getM));
list.sort(Comparator.comparing(Student::getM));
//单条件降序
list.sort(Comparator.comparing(Student::getM).reversed());
//多条件,nullsLast避免空值 naturalOrder按自然顺序比较可比较对象,返回序列化对象
list.sort(Comparator.comparing(Strudent::getM, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(Strudent::setX));
//自定义多条件
list.sort((user1,user2)->{
if (user1.getX().equals(user2.getX())) {
return user1.getM() - user2.getM();
} else {
return user1.getX().compareTo(user2.getX());
}
});
List>带有map集合特殊一点,通过“-”控制正序倒叙
List<Map<String, Object>> listMap = reList.stream().sorted((i, j) -> -(Convert.toInt(j.get("status"), 0) - Convert.toInt(i.get("status"), 0))).collect(Collectors.toList());
Integer[] archiIds = list.stream().filter(predicate->predicate.getCategoryId() == 1).mapToInt(ArchiParam :: getArchiId).boxed().toArray(Integer[]::new);
List<ArchiJournal> journals = journalService.getArchiExcels(archiIds);
List<ExcelJournal> excelJournals = journals.stream()
.map(mapper->{
ExcelJournal excelJournal = new ExcelJournal(mapper.getId(), mapper.getAchId(), mapper.getDataType(), mapper.getTitle(), mapper.getSource(), DateUtil.format(mapper.getPubTime(), "yyyy-MM-dd"), mapper.getAuthor(), mapper.getKeyword(), mapper.getInclude(), mapper.getSummary(), mapper.getDomain(), mapper.getStatus(), mapper.getYear(), mapper.getRoll(), mapper.getPeriod(), String.valueOf(mapper.getPageCount()), mapper.getPage(), mapper.getFundingLabel(), mapper.getDoi(), mapper.getOrgan(), mapper.getSrcDatabase(), mapper.getLink(), mapper.getDbProvider(), mapper.getLa(), mapper.getIsbn(), mapper.getCn(), null, null, mapper.getAuthor(), DateUtil.format(mapper.getCreateTime(), "yyyy-MM-dd"));
excelJournal.setFirstAuthers(mapper.getAuthorInfos().stream().filter(Author->Author.getIsFirst()).map(Author->new String(Author.getAuthorName())).collect(Collectors.joining(";")));
excelJournal.setContactAuthers(mapper.getAuthorInfos().stream().filter(Author->Author.getIsContact()).map(Author->new String(Author.getAuthorName())).collect(Collectors.joining(";")));
return excelJournal;
}).collect(Collectors.toList());