我正在尝试使用java快速代码删除复制,而不使用distinct。
这是我的解决方案:
public static List<Integer> dropDuplicates(List<Integer> list) {
return list
.stream()
.collect(Collectors.groupingBy(Function.identity()))
.values()
.stream()
.map(v -> v.stream().findFirst().get())
.collect(toList());
}它工作得很好,但元素的顺序改变了。
List<Integer> list = Arrays.asList(11, 12, 1, 2, 2, 3,12, 4, 13, 4, 13);
output => [1, 2, 3, 4, 11, 12, 13]我对java函数式编程有点陌生(也许这是个愚蠢的问题)。是否有任何方法来保持列表元素的顺序,或者其他更好的方法来做到这一点?
发布于 2021-02-08 10:07:08
您的问题来自这样一个事实,即Map接口在元素顺序方面没有任何保证。如果您关心订单,则需要确保使用有序的实现(如LinkedHashMap)。以下实现保留了该命令:
public static List<Integer> dropDuplicates(List<Integer> list) {
return list
.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.toList()))
.values()
.stream()
.map(v -> v.stream().findFirst().get())
.collect(Collectors.toList());
}当然,使用distinct()或欧内斯特的建议将是一种更简单的解决方案。只是想在你目前所做的基础上继续努力。
发布于 2021-02-08 10:11:49
您可以将filter函数与一个谓词一起使用,该谓词跟踪您已经看到的元素:
public <T> Predicate<T> distinct() {
final Set<T> seen = new HashSet<>();
return t -> {
if (seen.contains(t)) {
return false;
}
seen.add(t);
return true;
}
}现在你可以这样做了:
list.stream()
.filter(distinct())
.collect(toList());https://stackoverflow.com/questions/66099313
复制相似问题