it.setName("");returnit; }).collect(Collectors.toList()); System.out.println(list.toString()); 返回结果:[name=, age=30, name=, age=30] 4. 获取其中某个属性的集合: List collection =list.stream().map(Student::getAge).collect(Collectors.toList()); System.out.println(collection.toStrin...
前面已经说过Stream背后依赖于某种数据源,数据源可以是数组、容器等,但不能是Map。反过来从Stream生成Map是可以的,但我们要想清楚Map的key和value分别代表什么,根本原因是我们要想清楚要干什么。通常在三种情况下collect()的结果会是Map: 使用Collectors.toMap()生成的收集器,用户需要指定如何生成Map的key和value。 使...
Map<Long,String>map=userList.stream().collect(Collectors.toMap(User::getId,User::getName)); 这个获取的就是key为id,value为name的map了。 2. 三个参数的用法 还是沿用上面那个例子,如果这个时候你想获取key是age,value是name的map呢?如果你还是沿用上面的方法,就会出问题了,因为有两个age...
Map<String, Set<String>> map3 = Stream .of(Person.valueOf("China", "小明"), Person.valueOf("China", "小丽"), Person.valueOf("us", "Jack"), Person.valueOf("us", "Alice")) .collect(Collectors.toMap(Person::getCountry, p -> Collections.singleton(p.getName()), (x, y) -> {...
Map<Long,String> personIdNameMap = personList.stream().collect(Collectors.toMap(person ->preson.getId(),person ->preson.getName())); 上述的例子,是把personList(人员集合)提取内容,生成Map<人员id,人员名字>。 解析如下: 第一个参数person ->preson.getId()表示选择人员id作为map的key值;...
Map<String,Object> map = new HashMap<>(); map.put("name","张三1号"); map.put("age",1);; list.add(map); List<Map<String, Object>> res = list.stream().distinct().collect(Collectors.toList()); 1. 2. 3. 4. 5. ...
可以看到第三个consumer并没有被执行,在整个collect过程中,只创建了一个容器,然后将流中的数据添加到容器中,并不需要合并容器,将IntStream改成并行流 执行结果如下所示,在collect()过程创建了4个容器,执行了3次合并,将4个容器合并成最终结果容器并返回。方法二 这个方法和上面的不同是入参只有一个,只需要...
map():用于映射每个元素到对应的结果。以下代码片段使用 map 输出了元素对应的平方数: 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()); ...
public void filterEmployeesThenGroupByStream() { Map<String, List<Employee>> resultMap = getAllEmployees().stream() .filter(employee -> "上海公司".equals(employee.getSubCompany())) .collect(Collectors.groupingBy(Employee::getDepartment));
publicvoidfilterEmployeesThenGroupByStream(){Map<String,List<Employee>>resultMap=getAllEmployees().stream().filter(employee->"上海公司".equals(employee.getSubCompany())).collect(Collectors.groupingBy(Employee::getDepartment));System.out.println(resultMap);} ...