.map(t -> students.stream().filter(s -> Objects.nonNull(t.getName()) && Objects.nonNull(s.getName()) && Objects.equals(t.getName(), s.getName())).findAny().orElse(null)) .filter(Objects::nonNull) .map(r -> r.getName()) .collect(Collectors.toList()); 1. 2. 3. 4. 5....
collect(toList())方法由Stream里的值生成一个列表,是一个及早求值操作。可以理解为Stream向Collection的转换。 注意这边的toList()其实是Collectors.toList(),因为采用了静态倒入,看起来显得简洁。 List<String> collected = Stream.of("a", "b", "c") .collect(Collectors.toList()); assertEquals(Arrays.as...
List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList()); System.out.println("产生的新集合是:" + listNew); Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet()); System.out.println("产生的不重复的新集合...
//直接连接Stringjoin1=dishes.stream().map(Dish::getName).collect(Collectors.joining());//逗号Stringjoin2=dishes.stream().map(Dish::getName).collect(Collectors.joining(", ")); 5.2、toList Listnames=dishes.stream().map(Dish::getName).collect(toList()); 将原来的Stream映射为一个单元素流,...
collect\Collector\Collectors区别与关联 刚接触Stream收集器的时候,很多同学都会被collect,Collector,Collectors这几个概念搞的晕头转向,甚至还有很多人即使已经使用Stream好多年,也只是知道collect里面需要传入类似Collectors.toList()这种简单的用法,对其背后的细节也不甚了解。
Collectors.toMap(),一般用于将一个List转换为Map。常见用法: list.stream().collect(Collectors.toMap(Function keyMapper, Function valueMapper)) 可以接收2个、3个、4个参数,但是我一般只用2个的或者3个的就已经足够了。这里我也就只讲一个前两个用法,也就是2个参数的和3个参数的用法。
stream().map(Person::getName).collect(Collectors.toList()); // Accumulate names into a TreeSet Set<String> set = people.stream().map(Person::getName) .collect(Collectors.toCollection(TreeSet::new)); // Convert elements to strings and concatenate them, separated by commas String joined =...
所谓恒等处理,指的就是Stream的元素在经过Collector函数处理前后完全不变,例如toList()操作,只是最终将结果从Stream中取出放入到List对象中,并没有对元素本身做任何的更改处理: 恒等处理类型的Collector是实际编码中最常被使用的一种,比如: list.stream().collect(Collectors.toList()); ...
而使用Stream.collect(Collectors.toList())创建出来的则是一个普通的List,是可以做增删改操作的。 那么如果用Collectors也要创建不可变的List要怎么写呢?其实也很简单,只需要调用Collectors.toUnmodifiableList()就可以了。所以与本文开头等价代码替换可以这样写: ...
var words4 = words.stream().filter(word -> word.length() == 4) .collect(Collectors.toList()); With the stream method, we create a Java Stream from a list of strings. On this stream, we apply the filter method. The filter method accepts an anonymous function that returns a boolean ...