Java8 新特性之集合操作Stream
Stream简介
- Java 8引入了全新的Stream API。这里的Stream和I/O流不同,它更像具有Iterable的集合类,但行为和集合类又有所不同。
- stream是对集合对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作,或者大批量数据操作。
为什么要使用Stream
- 函数式编程带来的好处尤为明显。这种代码更多地表达了业务逻辑的意图,而不是它的实现机制。易读的代码也易于维护、更可靠、更不容易出错。
- 高端
使用实例:
测试数据:
1public class Data { 2 private static List<PersonModel> list = null; 3 4 static { 5 PersonModel wu = new PersonModel("wu qi", 18, "男"); 6 PersonModel zhang = new PersonModel("zhang san", 19, "男"); 7 PersonModel wang = new PersonModel("wang si", 20, "女"); 8 PersonModel zhao = new PersonModel("zhao wu", 20, "男"); 9 PersonModel chen = new PersonModel("chen liu", 21, "男"); 10 list = Arrays.asList(wu, zhang, wang, zhao, chen); 11 } 12 13 public static List<PersonModel> getData() { 14 return list; 15 } 16}
Filter
-
遍历数据并检查其中的元素时使用。
-
filter接受一个函数作为参数,该函数用Lambda表达式表示。
保留年龄为 20 的 person 元素 list = list.stream() .filter(person -> person.getAge() == 20) .collect(toList());
打印输出 [Person{name='jack', age=20}]
/** * 过滤所有的男性 */ public static void fiterSex(){ List<PersonModel> data = Data.getData();
1 //old 2 List<PersonModel> temp=new ArrayList<>(); 3 for (PersonModel person:data) { 4 if ("男".equals(person.getSex())){ 5 temp.add(person); 6 } 7 } 8 System.out.println(temp); 9 //new 10 List<PersonModel> collect = data 11 .stream() 12 .filter(person -> "男".equals(person.getSex())) 13 .collect(toList()); 14 System.out.println(collect); 15} 16 17/** 18 * 过滤所有的男性 并且小于20岁 19 */ 20public static void fiterSexAndAge(){ 21 List<PersonModel> data = Data.getData(); 22 23 //old 24 List<PersonModel> temp=new ArrayList<>(); 25 for (PersonModel person:data) { 26 if ("男".equals(person.getSex())&&person.getAge()<20){ 27 temp.add(person); 28 } 29 } 30 31 //new 1 32 List<PersonModel> collect = data 33 .stream() 34 .filter(person -> { 35 if ("男".equals(person.getSex())&&person.getAge()<20){ 36 return true; 37 } 38 return false; 39 }) 40 .collect(toList()); 41 //new 2 42 List<PersonModel> collect1 = data 43 .stream() 44 .filter(person -> ("男".equals(person.getSex())&&person.getAge()<20)) 45 .collect(toList()); 46 47}
distinct()
去除重复元素,这个方法是通过类的 equals 方法来判断两个元素是否相等的
如例子中的 Person 类,需要先定义好 equals 方法,不然类似[Person{name='jack', age=20}, Person{name='jack', age=20}] 这样的情况是不会处理的
参考:https://blog.csdn.net/haiyoung/article/details/80934467
limit(long n)
limit: 对一个Stream进行截断操作,获取其前N个元素,如果原Stream中包含的元素个数小于N,那就获取其所有的元素;
1返回前 n 个元素 2 3list = list.stream() 4 .limit(2) 5 .collect(toList()); 6 7打印输出 [Person{name='jack', age=20}, Person{name='mike', age=25}]
skip方法 :
skip: 返回一个丢弃原Stream的前N个元素后剩下元素组成的新Stream,如果原Stream中包含的元素个数小于N,那么返回空Stream;
Map
-
map生成的是个一对一映射,for的作用
-
比较常用
/** * 取出所有的用户名字 */ public static void getUserNameList(){ List<PersonModel> data = Data.getData();
1 //old 2 List<String> list=new ArrayList<>(); 3 for (PersonModel persion:data) { 4 list.add(persion.getName()); 5 } 6 System.out.println(list); 7 8 //new 1 9 List<String> collect = data.stream().map(person -> person.getName()).collect(toList()); 10 System.out.println(collect); 11 12 //new 2 13 List<String> collect1 = data.stream().map(PersonModel::getName).collect(toList()); 14 System.out.println(collect1); 15 16 //new 3 17 List<String> collect2 = data.stream().map(person -> { 18 System.out.println(person.getName()); 19 return person.getName(); 20 }).collect(toList()); 21}
filter 与 map 同时使用:
1List<String> collect = users.stream().filter(item -> { 2 if (!StringUtils.isEmpty(item.getUserName())) { 3 return true; 4 } 5 return false; 6 }).map(item -> item.getUserName()).collect(Collectors.toList());
FlatMap
-
顾名思义,跟map差不多,更深层次的操作
-
但还是有区别的
-
map和flat返回值不同
-
Map 每个输入元素,都按照规则转换成为另外一个元素。
还有一些场景,是一对多映射关系的,这时需要 flatMap。 -
Map一对一
-
Flatmap一对多
-
map和flatMap的方法声明是不一样的
-
- <r> Stream<r> map(Function mapper);
-
- <r> Stream<r> flatMap(Function> mapper);
-
map和flatMap的区别:我个人认为,flatMap的可以处理更深层次的数据,入参为多个list,结果可以返回为一个list,而map是一对一的,入参是多个list,结果返回必须是多个list。通俗的说,如果入参都是对象,那么flatMap可以操作对象里面的对象,而map只能操作第一层。
public static void flatMapString() { List<PersonModel> data = Data.getData(); //返回类型不一样 List<String> collect = data.stream() .flatMap(person -> Arrays.stream(person.getName().split(" "))).collect(toList());
1 List<Stream<String>> collect1 = data.stream() 2 .map(person -> Arrays.stream(person.getName().split(" "))).collect(toList()); 3 4 //用map实现 5 List<String> collect2 = data.stream() 6 .map(person -> person.getName().split(" ")) 7 .flatMap(Arrays::stream).collect(toList()); 8 //另一种方式 9 List<String> collect3 = data.stream() 10 .map(person -> person.getName().split(" ")) 11 .flatMap(str -> Arrays.asList(str).stream()).collect(toList()); 12}
map转list:
1Map<String, List<ProgrammeResult>> projectGroups = programmeResults.stream().collect(Collectors.groupingBy(ProgrammeResult::getProjectId)); 2 3 4 List<ProgrammeResult> fhSuccessResult = projectGroups.entrySet().stream().flatMap(item -> item.getValue().stream()).collect(Collectors.toList());
Collect
-
collect在流中生成列表,map,等常用的数据结构
-
toList()
-
toSet()
-
toMap()
/** * toList */ public static void toListTest(){ List<PersonModel> data = Data.getData(); List<String> collect = data.stream() .map(PersonModel::getName) .collect(Collectors.toList()); }
1/** 2 * toSet 3 */ 4public static void toSetTest(){ 5 List<PersonModel> data = Data.getData(); 6 Set<String> collect = data.stream() 7 .map(PersonModel::getName) 8 .collect(Collectors.toSet()); 9} 10 11/** 12 * toMap 13 */ 14public static void toMapTest(){ 15 List<PersonModel> data = Data.getData(); 16 Map<String, Integer> collect = data.stream() 17 .collect( 18 Collectors.toMap(PersonModel::getName, PersonModel::getAge) 19 ); 20 21 data.stream() 22 .collect(Collectors.toMap(per->per.getName(), value->{ 23 return value+"1"; 24 })); 25} 26 27/** 28 * 指定类型 29 */ 30public static void toTreeSetTest(){ 31 List<PersonModel> data = Data.getData(); 32 TreeSet<PersonModel> collect = data.stream() 33 .collect(Collectors.toCollection(TreeSet::new)); 34 System.out.println(collect); 35} 36 37/** 38 * 分组 39 */ 40public static void toGroupTest(){ 41 List<PersonModel> data = Data.getData(); 42 Map<Boolean, List<PersonModel>> collect = data.stream() 43 .collect(Collectors.groupingBy(per -> "男".equals(per.getSex()))); 44 System.out.println(collect); 45} 46 47/** 48 * 分隔 49 */ 50public static void toJoiningTest(){ 51 List<PersonModel> data = Data.getData(); 52 String collect = data.stream() 53 .map(personModel -> personModel.getName()) 54 .collect(Collectors.joining(",", "{", "}")); 55 System.out.println(collect); 56}
groupingBy 分组
groupingBy 用于将数据分组,最终返回一个 Map 类型
Map<Integer, List<Person>> map = list.stream().collect(groupingBy(Person::getAge));
例子中我们按照年龄 age 分组,每一个 Person 对象中年龄相同的归为一组
另外可以看出,Person::getAge 决定 Map 的键(Integer 类型),list 类型决定 Map 的值(List)
2.收集对象实体本身
- 在开发过程中我们也需要有时候对自己的list中的实体按照其中的一个字段进行分组(比如 id ->List),这时候要设置map的value值是实体本身。
1public Map<Long, Account> getIdAccountMap(List<Account> accounts) { 2 return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account)); 3}
account -> account是一个返回本身的lambda表达式,其实还可以使用Function接口中的一个默认方法 Function.identity(),这个方法返回自身对象,更加简洁
重复key的情况。
在list转为map时,作为key的值有可能重复,这时候流的处理会抛出个异常:Java.lang.IllegalStateException:Duplicate key。这时候就要在toMap方法中指定当key冲突时key的选择。(这里是选择第二个key覆盖第一个key)
1public Map<String, Account> getNameAccountMap(List<Account> accounts) { 2 return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2)); 3}
分组后统计每个组的数量:
Map<Integer, Long> items = list.stream().collect(Collectors.groupingBy(User::getUserName,Collectors.counting()));
多级分组
groupingBy 可以接受一个第二参数实现多级分组:
Map<Integer, Map<T, List<Person>>> map = list.stream().collect(groupingBy(Person::getAge, groupBy(...)));
partitioningBy 分区
分区与分组的区别在于,分区是按照 true 和 false 来分的,因此partitioningBy 接受的参数的 lambda 也是 T -> boolean
1根据年龄是否小于等于20来分区 2Map<Boolean, List<Person>> map = list.stream() 3 .collect(partitioningBy(p -> p.getAge() <= 20)); 4 5打印输出 6{ 7 false=[Person{name='mike', age=25}, Person{name='tom', age=30}], 8 true=[Person{name='jack', age=20}] 9}
【统计】
1 List<User> users = User.getUsers(); 2 int sum = users.stream().mapToInt(User::getUserAge).sum();//求和 3 System.out.println("sum==" + sum); 4 int max = users.stream().mapToInt(User::getUserAge).max().getAsInt();//最大 5 System.out.println("max==" + max); 6 int min = users.stream().mapToInt(User::getUserAge).min().getAsInt();//最小 7 System.out.println("min==" + min); 8 Double average = users.stream().mapToInt(User::getUserAge).average().getAsDouble();//平均值 9 System.out.println("average==" + average); 10 long count = users.stream().mapToInt(User::getUserAge).count(); // 得到元素个数 11 System.out.println("count===" + count); 12 13【参数匹配】 14 15 // allMatch 检测是否全部满足指定的参数行为 16 boolean b = users.stream().allMatch(User->User.getUserAge()>5); 17 System.out.println("allMatch,检测是否全部都满足指定的参数行为:"+b); 18 // anyMatch 检测是否存在一个或者多个满足指定的参数行为 19 boolean any = users.stream().anyMatch(User->User.getUserAge()>5); 20 System.out.println("anyMatch,检测是否存在一个或多个满足指定的参数行为:"+any); 21 // nonMatch 检测是否不存在满足指定行为的元素 22 boolean non = users.stream().noneMatch(User->User.getUserAge()>5); 23 System.out.println("检测是否不存在满足指定行为的元素:"+non); 24
参考博客:
https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/
https://www.jianshu.com/p/9fe8632d0bc2
https://cloud.tencent.com/developer/article/1187833
https://www.concretepage.com/java/jdk-8/java-8-distinct-example