java stream multiple map code example

Example 1: filter and map multiple fields from java stream

// Note that you shouldn't normally use == on objects
Predicate<Detail> itemPredicate = d-> item.equals(d.getItem());
Predicate<Detail> namePredicate = d-> name.equals(d.getName());

details.stream()
    .filter(itemPredicate.and(namePredicate))
    .collect(Collectors.toList());

Example 2: map multiple fields from java stream

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;
  };
}

Tags:

Java Example