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...
integers.stream().map(x -> x*x).collect(Collectors.toList()); // output: [1,4,9,16,25,36,36] 1. 2. 3. 返回Set集合: toSet() 用于将元素累积到Set集合中。它会删除重复元素。 List integers = Arrays.asList(1,2,3,4,5,6,6); integers.stream().map(x -> x*x).collect(Collect...
list.stream().map(it ->{ 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...
list = nums.stream().filter(num->num>3).collect(Collectors.toList()); 1. 2. 3. 4. 5. 6. 7. 8. 以上是通过filter来对数据进行过滤 实际上,对于stream流来说,生命周期大致可以分为三步:创建stream,操作stream,终止stream 创建stream 最简单易懂的操作,只要继承了Collection,就可以调用Stream方法生成...
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList()); filter():filter 方法用于通过设置的条件过滤出元素。以下代码片段使用 filter 方法过滤出空字符串: List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); ...
publicvoidfilterEmployeesThenGroupByStream(){Map<String,List<Employee>>resultMap=getAllEmployees().stream().filter(employee->"上海公司".equals(employee.getSubCompany())).collect(Collectors.groupingBy(Employee::getDepartment));System.out.println(resultMap);} ...
而使用Stream.collect(Collectors.toList())创建出来的则是一个普通的List,是可以做增删改操作的。 那么如果用Collectors也要创建不可变的List要怎么写呢?其实也很简单,只需要调用Collectors.toUnmodifiableList()就可以了。所以与本文开头等价代码替换可以这样写: ...
所以map函数的作用就是针对管道流中的每一个数据元素进行转换操作。 二、处理非字符串类型集合元素 map()函数不仅可以处理数据,还可以转换数据的类型。如下: List<Integer> lengths = alpha.stream() .map(String::length) .collect(Collectors.toList()); ...
1.抽取对象的code作为key,name作为value转化为map集合 方法为 private static HashMaplistToMap(ListpersonList) { return (HashMap)personList.stream() .filter(t -> t.getName()!=null) .collect(Collectors.toMap(Person::getCode,Person::getName,(k1,k2)->k2)); ...
有点类似Stream先进行了map操作再进行collect: servers.stream.map(s -> s.substring(1)).collect(Collectors.toList()); 3.11 reducing 这个方法非常有用!但是如果要了解这个就必须了解其参数BinaryOperator 。 这是一个函数式接口,是给两个相同类型的量,返回一个跟这两个量相同类型的一个结果,伪表达式为(T,T...