JAVA秒会技术之Java8新特性利用流快速处理集合的常见操作
Posted Ethan_LiYan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA秒会技术之Java8新特性利用流快速处理集合的常见操作相关的知识,希望对你有一定的参考价值。
例子1:对集合进行排序
List<Integer> list = Lists.newArrayList(1,1,2,2,5,3,4,6,6,5,2,7);
list.sort(null);
list.forEach(e -> System.out.print(e)); //输出结果:112223455667
例子2:对集合过滤
List<Integer> list = Lists.newArrayList(1,1,2,2,5,3,4,6,6,5,2,7);
list.removeIf(s-> s.equals(2));
list.forEach(e -> System.out.print(e)); //输出结果:115346657
例子3:集合1中的元素,同时存在在集合2中的(注意不会去重)
List<Integer> list1 = Lists.newArrayList(1,1,2,2,5,3,4,6,6,5,2,7);
List<Integer> list2 = Lists.newArrayList(1,1,3,5,7,8);
list1.retainAll(list2);
list1.forEach(e -> System.out.print(e)); //输出结果:115357
例子4:集合去重
List<Integer> list = Lists.newArrayList(1,1,2,2,5,3,4,6,6,5,2,7);
list = list1.stream().distinct().collect(Collectors.toList());
list.forEach(e -> System.out.print(e)); //输出结果:1253467
例子5:集合过滤(2)
List<Integer> list1 = Lists.newArrayList(1,1,2,2,5,3,4,6,6,5,2,7);
list1 = list1.stream().filter(s -> !s.equals(2)).collect(Collectors.toList());
list1.forEach(e -> System.out.print(e)); //输出结果:115346657
例子6:集合映射
User user1 = new User();
user1.setId(1);
user1.setUserName("张三");
User user2 = new User();
user2.setId(2);
user2.setUserName("李四");
User user3 = new User();
user3.setId(3);
user3.setUserName("王五");
User user4 = new User();
user4.setId(4);
user4.setUserName("赵六");
User user5 = new User();
user5.setId(5);
user5.setUserName("田七");
ArrayList<User> userList = Lists.newArrayList(user1,user2,user3,user4,user5);
List<String> userNameList = userList.stream().map(User :: getUserName).collect(Collectors.toList());
userNameList.forEach(e -> System.out.println(e)); //输出结果:张三 李四 王五 赵六 田七
例子7:List集合转换成Map集合
User user1 = new User();
user1.setId(1);
user1.setUserName("张三");
User user2 = new User();
user2.setId(2);
user2.setUserName("李四");
User user3 = new User();
user3.setId(3);
user3.setUserName("王五");
User user4 = new User();
user4.setId(4);
user4.setUserName("赵六");
User user5 = new User();
user5.setId(5);
user5.setUserName("田七");
ArrayList<User> userList = Lists.newArrayList(user1,user2,user3,user4,user5);
Map<Integer, String> userMap = userList.stream().collect(Collectors.toMap(User :: getId, User :: getUserName));
userMap.forEach((key,value) ->
System.out.println(key + ":" + value);
); //输出结果:1:张三 2:李四 3:王五 4:赵六 5:田七
其实流的应用还有很多,很强大,但是也有很多坑,大家自行摸索吧!
以上是关于JAVA秒会技术之Java8新特性利用流快速处理集合的常见操作的主要内容,如果未能解决你的问题,请参考以下文章