java 8 批量去重
Java 8中的Stream API提供了许多用于批量去重的方法。以下是一些常用的方法:
- 使用distinct()方法:通过调用distinct()方法,可以从流中去除重复的元素。
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3);
List<Integer> distinctNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(distinctNumbers); // 输出:[1, 2, 3, 4, 5]
- 使用collect()方法和toSet()方法:通过将流中的元素收集到Set集合中,可以自动去除重复的元素。
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3);
Set<Integer> distinctNumbers = numbers.stream()
.collect(Collectors.toSet());
System.out.println(distinctNumbers); // 输出:[1, 2, 3, 4, 5]
- 使用collect()方法和toMap()方法:通过将流中的元素收集到Map集合中,可以自动去除重复的键。
List<String> names = Arrays.asList("John", "Jane", "John", "Mary");
Map<String, Integer> distinctNames = names.stream()
.collect(Collectors.toMap(Function.identity(), String::length));
System.out.println(distinctNames); // 输出:{John=4, Jane=4, Mary=4}
- 使用collect()方法和toCollection()方法:通过将流中的元素收集到自定义集合中,可以实现批量去重。
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3);
List<Integer> distinctNumbers = numbers.stream()
.collect(Collectors.toCollection(() -> new ArrayList<>(new HashSet<>())));
System.out.println(distinctNumbers); // 输出:[1, 2, 3, 4, 5]
这些方法都可以帮助你在Java 8中实现批量去重的操作。根据具体的需求,选择适合的方法即可
原文地址: https://www.cveoy.top/t/topic/ivGz 著作权归作者所有。请勿转载和采集!