1、中文排序
// 升序(注意:是根据的汉字的拼音的字母排序的,而不是根据汉字一般的排序方法)
Collections.sort(list, Collator.getInstance(java.util.Locale.CHINA));
// 降序
Collections.reverse(list);
2、字符串排序 ->1.8
// 正序
list.stream().sorted(Comparator.comparing(String::valueOf));
// 倒序
list.stream().sorted(Comparator.comparing(String :: valueOf).reversed());
3、泛型排序
// 正序
list.stream().sorted(Comparator.comparing(StudyVO::getName)).collect(Collectors.toList());
// 倒序
list.stream().sorted(Comparator.comparing(StudyVO::getName).reversed()).collect(Collectors.toList());
4、根据某个属性或多个属性排序
list.stream().sorted(Comparator.comparing(StudyVO::getName).thenComparing(StudyVO::getGender);
5、去重
list.stream().distinct().collect(Collectors.toList());
6、根据某个属性去重,同时进行排序
list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->new TreeSet<>(Comparator.comparing(StudyVO::getId))), ArrayList::new));
7、根据某个属性去重
list.stream().filter(distinctByKey(obj -> obj.getId())).collect(Collectors.toList());public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {Map<Object, Boolean> params = new HashMap<>();return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
8、对多个对象去重
list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(obj -> obj.getId() + ";" + obj.getName()))), ArrayList::new));
9、分组
// 单个条件
Map<String, List<StudyVO>> groupedMap = list.stream().collect(Collectors.groupingBy(obj -> obj.getGrade()));// 多个条件
Map<String, List<StudyVO>> groupedMap = list.stream().collect(Collectors.groupingBy(obj -> obj .getGrade() +“|” +obj.getType()));
10、过滤
// 过滤name为flm
list.stream().filter(obj ->"flm".equals(obj.getName())).collect(Collectors.toList());// 也可以使用方法返回false/true
list.stream().filter(obj ->{if("flm".equals(obj .getName())){return false;}else{return true;}}).collect(Collectors.toList());
11、合并集合某个属性
List<UserVO> newvos = list.stream().collect(Collectors.toMap(BillsNums::getId, a -> a, (obj1, obj2)-> {obj1.setNums(obj1.getNums() + obj2.getNums());obj1.setSums(obj1.getSums() + obj2.getSums());return obj1;})).values().stream().collect(Collectors.toList());
12、截取,用于逻辑分页
list.stream().limit(n).collect(Collectors.toList());
13、转字符串并加入分隔符
import org.apache.commons.lang.StringUtils;List<String> list = new ArrayList<String>();
list.add("first");
list.add("second");
list.add("third");StringUtils.join(list.toArray(), ",")
14、获取最大值,数字集合
list.stream().max(Integer::comparaTo)).get();
15、获取最大对象,泛型
list.stream().max(Comparator.comparing(Study::getAge)).collect(Collectors.toList());