Stream的常见用法

Stream的常见用法

前言:前面有篇文章介绍过Stream流的使用,但是只是理解,不去使用的话,每次遇到相关的代码还是会感觉有点难理解;学只是凡是要一点一点来吧,要想看一篇stream的文章就直接能在工作熟练使用那…反正我不行。所以遇到了在记录一下,多反思理解两次自然就会了…反正我行;想多了解一下stream可以看一下我之前的java8新特性的文章。

//1.将集合中的数据收集到list/set中
List<User> userList = list.stream().collect(Collectors.toList());
System.out.println(userList.toString());

//2.如果集合中存储的对象,也可以将对象中的属性值收集到list/set中;
List<String> userName = userList.stream().map(User::getName).collect(Collectors.toList());
System.out.println("2. 将集合中user对象的某个属性收集到list/set中:"+userName+"\r\n");

//3.对集合中的数据进行一个过滤
List<String> lee = userName.stream().filter(e -> e.contains("lee")).collect(Collectors.toList());
System.out.println(lee);

//4.对stream的字符串拼接返回一个新的字符串,(尝试将收集到list中的name进行拼接)
String collect1 = userName.stream().collect(Collectors.joining(", "));
System.out.println(collect1);

//5.如果集合中存储的对象,我们还可以将作为两个属性对应,收集到一个map集合中
Map<String, String> collect = userList.stream().collect(Collectors.toMap(User::getName, User::getAddr));
System.out.println(collect);

输出:

1. [User{name='lisi', addr='上海'}, User{name='leejie', addr='深圳'}]
2. [lisi, leejie]
3. [leejie]
4. lisi, leejie
5. {leejie=深圳, lisi=上海}

所以stream是对集合进行一个新的处理,然后返回给我们需要的数据和格式,在我们需要对集合进行类型转换或者是提取集合中有用的数据时,都是可以使用这个快捷方式的,一行代码搞定,省的我们像以前一样去遍历数组,然后在对数据进行处理。

如果不会用stream特性的,像我们第二个例子,将集合中对象的属性提取到新的list中,代码可能就是这样子的了:

ArrayList<String> strings = new ArrayList<>();
for (User user2 : userList) {
    
    
   strings.add(user2.getName());
}

//等价于
userList.stream().map(User::getName).collect(Collectors.toList());

看着也还好,但还是要多去接受新的技术才行嘛。(其实也是想说明一下这两个是等价的,方便理解)

总结:

说白了就是个对集合处理的一种快捷方式,但是如果看到别人的代码这样写,看不懂的话就尴尬了;所以我觉得暂时常用得能会用就行(要探究源码也是可以的),多看多写慢慢理解;

下一篇:java的编码解码

おすすめ

転載: blog.csdn.net/weixin_43573186/article/details/121580218