Set<String> result = Stream.of("aa", "bb", "cc", "aa").collect(HashSet::new, HashSet::add, HashSet::addAll); //Collectors类中已经预定义好了toList,toSet,toMap,toCollection等方便使用的方法,所以以上代码还可以简化如下: Set<String> result2 = Stream.of("aa", "bb", "cc", "aa")...
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...
发现的确是同事使用了类似stringList.stream().filter(number -> Long.parseLong(number) > 1).toList()以stream.toList()作为返回, 后继续使用了返回值做add操作,导致报错 2. StreamtoList()和collect(Collectors.toList())的区别 JDK version: 21 IDE: IDEA 从Java16开始,Stream有了直接toList方法, java8...
而使用Stream.collect(Collectors.toList())创建出来的则是一个普通的List,是可以做增删改操作的。 那么如果用Collectors也要创建不可变的List要怎么写呢?其实也很简单,只需要调用Collectors.toUnmodifiableList()就可以了。所以与本文开头等价代码替换可以这样写: ...
stream写法 long count = persons.stream() .filter(person -> person.getAge() > 20) .count(); 1. 2. 3. 大大简化了 二,常用操作 1,collect collect(toList())方法由Stream里的值生成一个列表,是一个及早求值操作。可以理解为Stream向Collection的转换。
1/** 2 * 二级分组示例 3 * @param shopCars 4 */ 5public static void test_level_group(List<ShopCar> shopCars) { 6 Map<String, Map<String, List<ShopCar>>> result = 7 shopCars.stream().collect(Collectors.groupingBy(ShopCar::getSellerName, 8 Collectors.groupingBy(ShopCar::getBuyerName))...
1.2.Stream.collect(Collectors.toUnmodifiableList()) This method has beenadded in Java 10. It is aterminal operationthat collects the stream items into anunmodifiable List. The returned list is an instance ofCollections.unmodifiableList()that is filled with stream items using JDK internal APIs able ...
collect(Collectors.toSet()) collect(Collectors.toMap()) publicclassStreamCollectCollectorsXXX {publicstaticvoidmain(String[] args) { Stream<String> persons = Stream.of("张三","李四","王五");//List<String> personList = persons.collect(Collectors.toList());//Set<String> personSet = persons....
本文主要介绍Java通过stream()对List(列表)操作的常用方法。 1、遍历操作(map) 使用map操作可以遍历集合中的每个对象,并对其进行操作,map之后,用.collect(Collectors.toList())会得到操作后的集合。 1)遍历转换为大写 List<String> output = wordList.stream(). ...
收集器(Collector)是为Stream.collect()方法量身打造的工具接口(类)。考虑一下将一个Stream转换成一个容器(或者Map)需要做哪些工作?我们至少需要两样东西: 目标容器是什么?是ArrayList还是HashSet,或者是个TreeMap。 新元素如何添加到容器中?是List.add()还是Map.put()。如果并行的进行规约,还需要告诉collect() ...