stream().map(Person::getId).collect(Collectors.toList()); //2.提取出list对象中的一个属性并去重 List<String> stIdList2 = stuList.stream().map(Person::getId).distinct().collect(Collectors.toList()); 发布者:全栈程序员栈长,转载请注明出处:http
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流特性的伙伴们都知道,它在很大程度上简化了我们的代码。 那么,上面提到的作用,具体怎么实现呢?
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<String, List<Employee>> resultMap = getAllEmployees().stream() .filter(employee -> "上海公司".equals(employee.getSubCompany())) .collect(Collectors.groupingBy(Employee::getDepartment)); System.out.println(resultMap); } 两种写法都可以得到相同的结果: ...
.filter(word -> word.length() > 5) .sorted((o1, o2) -> o2.length() - o1.length()) .limit(3) .collect(Collectors.toList()); } 直观感受上,Stream的实现方式代码更加简洁、一气呵成。很多的同学在代码中也经常使用Stream流,但是对Stream流的认知往往也是仅限于会一些简单的filter、map、collect...
Map<Long,String> personIdNameMap = personList.stream().collect(Collectors.toMap(person ->preson.getId(),person ->preson.getName())); 上述的例子,是把personList(人员集合)提取内容,生成Map<人员id,人员名字>。 解析如下: 第一个参数person ->preson.getId()表示选择人员id作为map的key值; ...