Map<String, User> maps3 = list.stream().collect (Collectors.toMap(User::getName,Function.identity(),(k1, k2) -> k1,LinkedHashMap::new)); 输出结果 {pangHu=User{name='pangHu', age=18}, piKaQiu=User{name='piKaQiu', age=15}, laoBi=User{name='laoBi', age=20}, wangHao=User{name...
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);//获取对应的平方数List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList()); filter():filter 方法用于通过设置的条件过滤出元素。以下代码片段使用 filter 方法过滤出空字符串: List<...
List<Students>data= studentsList.stream().filter(s->s.getMath()>90).collect(Collectors.toList()); 我们也可以多次筛选,比如除了上面的条件,我们再加入筛选判断大于等于18岁的人。 List<Students>data= studentsList.stream().filter(s->s.getMath()>90).filter(x->x.getAge()>=18).collect(Collecto...
(1)filter:从集合中筛选出符合条件的数据。 (2)distinct:对集合中重复的元素去重。 (3)collect:对集合进行的一系列关系映射。 (4)map:获取集合中某类数据的集合 使用过Java8流特性的伙伴们都知道,它在很大程度上简化了我们的代码。 那么,上面提到的作用,具体怎么实现呢?
publicvoidfilterEmployeesThenGroupByStream(){Map<String,List<Employee>>resultMap=getAllEmployees().stream().filter(employee->"上海公司".equals(employee.getSubCompany())).collect(Collectors.groupingBy(Employee::getDepartment));System.out.println(resultMap);} ...
Stream<Person>filteredStream=personStream.filter(person->person.age>28); 1. 4. 使用 map 方法提取字段 现在,我们使用map()方法来提取过滤后的人的name字段。 Stream<String>nameStream=filteredStream.map(Person::getName); 1. 5. 收集结果 最后,我们使用collect()方法将结果收集到一个List中。
Map<Long,String> personIdNameMap = personList.stream().collect(Collectors.toMap(person ->preson.getId(),person ->preson.getName())); 上述的例子,是把personList(人员集合)提取内容,生成Map<人员id,人员名字>。 解析如下: 第一个参数person ->preson.getId()表示选择人员id作为map的key值; ...
stringCollection .stream() .filter((s) -> s.startsWith("a")) .forEach(System.out::println);Map 这个功能也是遍历,但是他是有返回值的,而上面的 Foreach 是没有返回值的,仅仅是单纯的消费。而且 Foreach 不能够链式调用,因为没有返回值,但是 Map 没问题。stringCollection .stream()...
Map<String, List<Employee>> resultMap = getAllEmployees().stream() .filter(employee -> "上海公司".equals(employee.getSubCompany())) .collect(Collectors.groupingBy(Employee::getDepartment)); System.out.println(resultMap); } 两种写法都可以得到相同的结果: ...