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.
Now let l1 has the following properties(name, price) :-
n1, p1
n1, p2
n2, p1
n2, p3
Now after the filter the list should be-
n1, p1
n2, p3
I tried solving like this -
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;
}
Now the problem is when i did filter on name the list return would be -
n1, p1
n2, p1
and then it would have run filter on price which return -
n1, p1
which is not the expected result.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…