jdk1.8list的stream流常用总结

1.过滤filter

//过滤filter:获取年龄大于22的用户
list.stream().filter(user -> user.getAge() > 22).collect(Collectors.toList());

2.去重

//去重:按照所有字段
list.stream().distinct().collect(Collectors.toList());
//去重:按照一个字段
list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(user -> user.getUserName()))), ArrayList::new));
//去重:按照多个字段
 list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(user -> user.getUserName()+";"+user.getAge()))), ArrayList::new));

3.排序

//排序:按照单个字段,默认升序
list = list.stream().sorted(Comparator.comparing(user -> user.getId())).collect(Collectors.toList());
//排序:按照多个字段,默认升序
list.stream().sorted(Comparator.comparing(User::getId).thenComparing(User::getAge)).collect(Collectors.toList());
//排序:按照多个字段,有升序,有降序
 list = list.stream().sorted(Comparator.comparing(User::getId).reversed().thenComparing(User::getAge)).collect(Collectors.toList());
//排序:
	list = list.stream().sorted(Comparator.comparing(node -> ((node == null || node.toString().split("_").length == 0 || StringUtil.isEmpty(node.toString().split("_")[1])) ? "0" : node.toString().split("_")[1])).thenComparing(node -> ((node == null || node.toString().split("_").length == 0 || StringUtil.isEmpty(node.toString().split("_")[0])) ? "0" : node.toString().split("_")[0]))).collect(Collectors.toList());
		

4.拼接

//拼接
String result = list.stream().map(User::getUserName).collect(Collectors.joining(","));

5.转map

//转为map
Map> map = list.stream().collect(Collectors.groupingBy(User::getUserName));

你可能感兴趣的:(Java基础,list,java,数据结构)