1、使用toCollection和TreeSet去重 TreeSet内部使用的是TreeMap,使用指定Comparator比较元素,如果元素相同,则新元素代替旧元素。 List<TalentPlanStudentEntity> studentList = relatePlanStudentList.stream() .collect(Collectors.collectingAndThen(Collectors.toCollection( () ->newTreeSet<>(Comparator.comparing(TalentPl...
Set:接口,继承Collecthion ArrayList:实现类 packagecom.itheima.d1_collection;importjava.util.ArrayList;importjava.util.Collection;importjava.util.HashSet;/**目标:明确Collection集合体系的特点*/publicclassCollectionDemo1 {publicstaticvoidmain(String[] args) {// 有序 可重复 有索引 List家族Collection list...
collect(Collectors.toCollection(TreeSet::new)); // TreeSet:[1001, 1002, 1003, 1004, 1005] 注意:toList方法返回的是List子类,toSet返回的是Set子类,toCollection返回的是Collection子类。Collection的子类包括List、Set等众多子类,所以toCollection更加灵活。 2. 聚合元素:toMap、toConcurrentMap 这两个方法的...
toList()); // 获取所有的name转换到Set<String>中 Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new)); // 元素转换为String 并且将他们通过", " 连接起来 String joined = things.stream() .map(Object::toString) .collect(Collectors.joining("...
Set<String>set=Stream.of(null,"a",null,"b").filter(Objects::nonNull).collect(Collectors.toSet());System.out.println(set);// 输出: [a, b] 1. 2. 3. 4. 5. 在上面的代码示例中,我们使用Stream.of方法创建一个包含空元素和非空元素的流。然后使用filter方法筛选出非空元素,并使用collect方法...
collect(Collectors.toSet()); System.out.println(filteredFruits); // 输出 [apple] 8.3.8 使用 forEach 遍历元素 Java 8 引入的 forEach 方法可以方便地遍历集合中的元素。 代码语言:javascript 代码运行次数:0 运行 AI代码解释 Set<String> fruits = new HashSet<>(Arrays.asList("apple", "banana", ...
Map<Integer, List<AppMenuTree>> parentMap = menuList.stream() .collect(Collectors.groupingBy(AppMenuTree::getParentId)); for (Entry<Integer, List<AppMenuTree>> entry : parentMap.entrySet()) { List<AppMenuTree> childMenus = entry.getValue(); ...
.collect(Collectors.toList()); uniquePersons.forEach(System.out::println); } } 代码解释: 定义Person类:包含id、name和age字段,并重写hashCode和equals方法。 创建List对象:包含多个Person对象,其中有重复的对象。 使用Stream API去重:调用stream()方法生成流,使用distinct()方法去重,并收集到新的列表中。
* 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 = things.stream() * .map(Object::toString) ...
我们可以使用Collectors类的toCollection()方法来创建一个新的Collection,并使用该Collection的add()方法将元素添加到集合中,如果元素已存在,则不会添加。示例代码:List numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);Collection uniqueNumbers = numbers.stream().collect(Collectors.toCollection(HashSet::...