Java8新特性

分组:↓

Map<BigDecimal, Set<String>> result =
                items.stream().collect(
                        Collectors.groupingBy(Item::getPrice,
                                Collectors.mapping(Item::getName, Collectors.toSet())
                        )
                );
Map<BigDecimal, Set<Object>> result =
                items.stream().collect(
                        Collectors.groupingBy(Item::getPrice)
              )
                ); Set
<Map<String, Object>> moduleProjectListGroup = moduleProjectList.stream(). collect(Collectors.groupingBy(e -> e.get("projectName"))).entrySet().stream().map(e -> { Map<String, Object> map = new HashMap<>(); map.put("moduleList", e.getValue()); map.put("projectName", e.getKey()); return map; }).collect(Collectors.toSet()); 其中moduleList是一个List<Map<String,Object>>数据类型

 统计:↓

list.stream().mapToDouble(User::getHeight).sum()//
list.stream().mapToDouble(User::getHeight).max()//最大
list.stream().mapToDouble(User::getHeight).min()//最小
list.stream().mapToDouble(User::getHeight).average()//平均值 
其中支持还支持toInt, toLong,若是要统计BigDecimal则可以如下操作:
list.stream().map(User::getHeight).reduce(BigDecimal.ZERO, BigDecimal::add);

注意:以上都不会自动过滤null所以在使用的时候要结合filter使用过滤非法数据 


 归约:↓

reduce(可以实现统计sum,min等操作以及字符串拼接)
int totalAge2 = students.stream()
                .filter(student -> "信息与计算科学".equals(student.getMajor()))
                    .map(Student::getAge)
                        .reduce(0, Integer::sum);

工作流程:过滤出信息与计算科学的学生,并对学生的成绩进行求和

比较:上面的做法和mapToInt效果相同

int totalAge = students.stream()
                        .filter(student -> "计算机科学".equals(student.getMajor()))
                            .mapToInt(Student::getAge).sum();

可以发现reduce的用法适用的范围较广,通过查询资料,sum,min,max以及average等都是特殊的reduce


过滤:↓
 1. filter(最基础的过滤操作):

(List<Student>)list.stream()
                   .filter(student -> "东华理工大学".equals(student.getSchool()))

工作流程:过滤东华理工大学的学生

2. distinct(带有去重的过滤操作,基于equals操作):

(List<Integer>)nums.stream()
                       .filter(num -> num % 2 == 0)
                         .distinct()
                          .collect(Collectors.toList());

工作流程:过滤除以2余数为0的数,并且去除重复的值输出,其中distinct是利用Integer的equals实现的

 3. limit(过滤并限制输出的集合大小):

 (List<Student>)students.stream()
                          .filter(student -> "信息与计算科学".equals(student.getMajor()))
                            .limit(2)
                              .collect(Collectors.toList());

工作流程:先过滤出信息与计算科学的学生,然后选取前两个输出

 4. sorted(过滤并实现排序):

(List<Student>)students.stream()
                                             .filter(student -> "信息与计算科学".equals(student.getMajor())).sorted((s1, s2) -> s1.getAge() - s2.getAge())
                                                .limit(2)
                                                    .collect(Collectors.toList())

工作流程:先过滤出信息与计算科学的学生,然后根据其年龄升序排序,并输出最前面两个

默认升序排序

list.stream().sorted() 

自然序逆序元素,使用Comparator 提供的reverseOrder() 方法

list.stream().sorted(Comparator.reverseOrder()) 

使用Comparator 来排序一个list

list.stream().sorted(Comparator.comparing(Student::getAge)) 

把上面的元素逆序

list.stream().sorted(Comparator.comparing(Student::getAge).reversed()) 

 

5. skip(过滤并跳过N个元素取其后面的元素):

List<Student> civilStudents = students.stream()
                                     .filter(student -> "信息与计算科学".equals(student.getMajor()))
                                         .skip(2)
                                            .collect(Collectors.toList());

工作流程:先过滤出信息与计算科学的学生,然后输出前两个学生之后的学生                


映射:↓
1.map(将某个对象映射成其他对象):

List<String> students.stream()
                            .filter(student -> "信息与计算科学".equals(student.getMajor()))
                                .map(Student::getName).collect(Collectors.toList());

工作流程:将信息与计算科学的学生list映射成名字list

 2.flatMap(将一个流中的每个值都转成一个个流,然后再将这些流扁平化成为一个流 ):

List<String> list = Arrays.asList("hello welcome", "world hello", "hello world",  
            "hello world welcome");  
list.stream()
                  .flatMap(item -> Arrays.stream(item.split(" ")))
                    .distinct()
                        .collect(Collectors.toList())
                            .forEach(System.out::println); 

工作流程:先将每一个元素采用空格切割成一个数组,这样就会得到四个数组,然后将四个数组扁平化成一个数组去重输出

输出结果:hello  welcome  world


查找:↓
1.allMatch(匹配所有满足条件之后则返回true):

(List<Sdudent>)students.stream().allMatch(student -> student.getAge() >= 18);

工作流程:集合中所有学生年龄在18岁以上(包含18岁)则返回true否则false

同理有anyMatch(只要一个满足要求就返回true)、noneMatch(没有一个满足要求则返回true)

 2.findFirst(返回满足条件的第一个元素):

List<Student>students.stream().filter(student -> "土木工程".equals(student.getMajor())).findFirst().get();

工作流程:略

同理有findAny(随机返回一个满足条件的元素)


List、Map互转 ↓

1.List2Map

List<TreeNode> treeNodes = new ArrayList();
Map<Long, TreeNode> districtIdToRootTreeNode = treeNodes.stream().collect(Collectors.toMap(TreeNode::getId, treeNode -> treeNode));

2.Map2List

Map map=new HashMap<>();
map.put("1","AAAA");
map.put("2","BBBB");
map.put("3","CCCC");
map.put("4","DDDD");
map.put("5","EEEE");
List list= map.entrySet().stream().map(et ->et.getKey()+"_"+et.getValue()).collect(Collectors.toList());

LIST 切分

1.使用google guava的工具类Lists

// 每十个为一组,分成多组进行处理
List<List<User>> parts = Lists.partition(list, 10).forEach(part -> { //TODO });

资料参考:
探究原理参考资料:https://juejin.im/post/59c7d4c8f265da0650753328
总结以上参考资料:https://www.cnblogs.com/shenlanzhizun/p/6027042.html;https://www.cnblogs.com/netoxi/p/10346539.html
java8中stream详细api参考资料:https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html
 

原文地址:https://www.cnblogs.com/lzj123/p/9163009.html