java 8 how to get distinct list on more than one property(java 8如何在多个属性上获得不同的列表)
问题描述
如何从对象列表中获取不同的(基于两个属性的不同)列表.例如,让有属性名称和价格的对象列表.现在我如何才能获得具有不同名称或价格的列表.
假设
How can one get the distinct (distinct based on two property) list from a list of objects.
for example let there are list of objects with property name and price.
Now how can I get a list with distinct name or price.
suppose
list<xyz> l1 = getlist(); // getlist will return the list.
现在让 l1 具有以下属性(名称、价格):-
n1, p1
n1, p2
n2, p1
n2, p3
Now let l1 has the following properties(name, price) :-
n1, p1
n1, p2
n2, p1
n2, p3
现在过滤后的列表应该是-
n1, p1
n2, p3
Now after the filter the list should be-
n1, p1
n2, p3
我试过这样解决 -
public List<xyz> getFilteredList(List<xyz> l1) {
return l1
.stream()
.filter(distinctByKey(xyz::getName))
.filter(distinctByKey(xyz::getPrice))
.collect(Collectors.toList());
}
private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object,Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
现在的问题是,当我对名称进行过滤时,列表返回将是 -
n1, p1
n2, p1
Now the problem is when i did filter on name the list return would be -
n1, p1
n2, p1
然后它会对返回的价格运行过滤器 -
n1, p1
and then it would have run filter on price which return -
n1, p1
这不是预期的结果.
推荐答案
我会选择这样的东西,它相当简单灵活,并且基于您的示例:
I'd go for something like this, which is fairly simple and flexible, and builds on your example:
public static <T> List<T> distinctList(List<T> list, Function<? super T, ?>... keyExtractors) {
return list
.stream()
.filter(distinctByKeys(keyExtractors))
.collect(Collectors.toList());
}
private static <T> Predicate<T> distinctByKeys(Function<? super T, ?>... keyExtractors) {
final Map<List<?>, Boolean> seen = new ConcurrentHashMap<>();
return t -> {
final List<?> keys = Arrays.stream(keyExtractors)
.map(ke -> ke.apply(t))
.collect(Collectors.toList());
return seen.putIfAbsent(keys, Boolean.TRUE) == null;
};
}
然后可以通过以下方式调用它:
This can then be called in the following manner:
final List<Xyz> distinct = distinctList(list, Xyz::getName, Xyz::getPrice)
这篇关于java 8如何在多个属性上获得不同的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java 8如何在多个属性上获得不同的列表
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01