# list
# 通过tree set 去重
List<Student> studentDistinctList = studentList.stream()
.collect(Collectors.collectingAndThen
(Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(t -> t.getName()))),
ArrayList::new
)
);
System.out.println(new Gson().toJson(studentDistinctList));
# 扩展distinct 方法去重
List<Student> studentDistinct2List = studentList.stream().filter(StreamUtil.distinctByKey(t->t.getName()))
.collect(Collectors.toList());
System.out.println(new Gson().toJson(studentDistinct2List));
public class StreamUtil {
/**
* https://stackoverflow.com/questions/23699371/java-8-distinct-by-property
* @param keyExtractor
* @param <T>
* @return
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
}
filter去重
public <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
.stream().filter(distinctByKey(Org::getFullName)).collect(Collectors.toList());
# 排序
//按照List中对象的id属性升序
list.sort(Comparator.comparing(Stu::getId))
//按照List中对象的id属性降序
list.sort(Comparator.comparing(Stu::getId).reversed());
//多条件升序
list.sort(Comparator.comparing(Stu::getId).thenComparing(Stu::getSid));
//id升序,sid降序
list.sort(Comparator.comparing(Stu::getId).reversed().thenComparing(Stu::getSid));
//key值重复的map
MultiValueMap<Integer, String> timeMap = new LinkedMultiValueMap<>();
//集合升序排序
Collections.sort(student, new Comparator(){
public int compare(StudentVo p1, StudentVo p2) {
return Integer.parseInt(p1.getStudentCode()) - Integer.parseInt(p2.getStudentCode());
}
});