珍惜当下 展望未来!

java8 stream流的常用操作

stream流的常用操作

1.数据准备:

构建list

public static List<User> list() {
        List<User> list = new ArrayList<>();
        list.add(new User("孙悟空", 12));
        list.add(new User("猪八戒", 23));
        list.add(new User("沙僧", 22));
        list.add(new User("唐僧", 45));
        return list;
    }

2.stream操作

1.list转map

//属性映射属性
Map<String, Integer> map = list().stream().collect(Collectors.toMap(User::getName, User::getAge));
//属性映射实体
Map<String, User> map1 = list().stream().collect(Collectors.toMap(User::getName, Function.identity()));

2.map转list

//map中所有的value转换为list
List<User> list = new ArrayList<>(map1.values());              

3.提取list中实体的某个字段,生成一个新的list

 List<String> list1 = list.stream().map(User::getName).collect(Collectors.toList());      

4.过滤list

List<User> list2 = list().stream().filter(user -> user.getName().contains("孙")).collect(Collectors.toList());       

5.分页

long offset = 0; 
long limit = 1; 
List<User> list3 = list().stream().skip(offset).limit(limit).collect(Collectors.toList());              

6.聚合

int sum = list().stream().mapToInt(User::getAge).sum(); 
int max = list().stream().mapToInt(User::getAge).max().getAsInt(); 
int min = list().stream().mapToInt(User::getAge).min().getAsInt();
double average = list().stream().mapToDouble(User::getAge).average().getAsDouble();              

7.逗号字符串转list

String s = "12345,232434,      54354534 "; 
//转为 List<String>
List<String> list4 = Arrays.asList(s.split(","));
//转为 List<Long>              
List<Long> collect = Arrays.asList(s.split(",")).stream().map(o -> Long.parseLong(o.trim())).collect(Collectors.toList()); 

8.将list转为逗号字符串

//list转逗号字符串
List<String> strs = new ArrayList<>(); 
strs.add("孙悟空"); strs.add("猪八戒"); strs.add("唐僧"); strs.add("沙僧");
String collect1 = strs.stream().map(String::valueOf).collect(Collectors.joining(","));  



String collect = list().stream().map(User::getName).collect(Collectors.joining(","));

排序:

//倒序并把null值排到最后
list.stream().sorted(Comparator.comparing(User::getNum, Comparator.nullsFirst(Double::compareTo)).reversed())        .collect(Collectors.toList());          

分组

Map<String, List<WorkAreaTreeVO>> map = treeVOS.stream().collect(Collectors.groupingBy(WorkAreaTreeVO::getAttrValue));
			

根据多个字段去重

list = list.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(p->p.getName1() + ";" + p.getName2()))), ArrayList::new));

posted @ 2021-12-17 15:08  嘿嘿-  阅读(1393)  评论(0编辑  收藏  举报