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...
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...
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...
//使用java8 api方法list.stream().map().collect(Collectors.toList()) //userList User实体类对象集合 //User 实体类 //getId 实体类属性的get方法 List<int> ids= userList.stream().map(User::getId).collect(Collectors.toList()) //或者 把数据放到map根据user.getId(条件) 循环 在转换成list List...
2,map 如果有一个函数可以将一种类型的值转换成另外一种类型,map操作就可以使用该函数,将一个流中的值转换成一个新的流 List<String> collected = Stream.of("a", "b", "hello") .map(string -> string.toUpperCase()) .collect(toList()); ...
1. 聚合元素:toList、toSet、toCollection 这几个函数比较简单,是将聚合之后的元素,重新封装到队列中,然后返回。对象数组一般搭配map使用,是最经常用到的几个方法。比如,得到所有Person的Id 列表,只需要根据需要的结果类型使用不同的方法即可: people.stream().map(Person::getId).collect(Collectors.toList())...
Map<String,String>map=list.stream().collect(Collectors.toMap(Person::getId,Person::getName,(key1,key2)->key2));System.out.println(map); 输出结果: 2.重复时将前面的value 和后面的value拼接起来; 代码语言:javascript 代码运行次数:0 运行 ...
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)); ...
public void filterEmployeesThenGroupByStream() { Map<String, List<Employee>> resultMap = getAllEmployees().stream() .filter(employee -> "上海公司".equals(employee.getSubCompany())) .collect(Collectors.groupingBy(Employee::getDepartment));
而使用Stream.collect(Collectors.toList())创建出来的则是一个普通的List,是可以做增删改操作的。 那么如果用Collectors也要创建不可变的List要怎么写呢?其实也很简单,只需要调用Collectors.toUnmodifiableList()就可以了。所以与本文开头等价代码替换可以这样写: ...