1) Use a utility method distinctbykey
in filter
if you want to get unique result on some field.
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
ArrayList<X> items = new ArrayList();
items = items
.stream()
.filter( distinctByKey(x -> x.uniqueFiled()) ) // pass field of X object on basis of you want unique objects
.collect(Collectors.toList());
2) There is another way to get no duplication in list.
Override
equals
and hash
function of X
class in which you have to compare Brand
field and then use distinct method of stream
it will return distinct objects list by calling of your equals
and hash
function.
ArrayList<X> items = new ArrayList();
items = items
.stream()
.distinct()
.collect(Collectors.toList());
3) If you implement equals
and hash
functions. then simply create a Set
from List
. Set
has unique elements and ten again create List
from that Set
.
ArrayList<X> items = new ArrayList();
Set<X> set = new HashSet<X>(items); // Now set has unique elements
items = set.stream().collect(Collectors.toList()); // list have unique elemets too