Solution 1
Once you tie your equals functions in your Objects/Beans, you can use distinct function in streams.
public class BeanLevel {
public long id;
@Override
public int hashCode() {
int hash = 7;
hash = 43 * hash + (int) (this.id ^ (this.id >>> 32));
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
BeanLevel other = (BeanLevel) obj;
return Objects.equals(id, other.id);
}
}
public static List<BeanLevel> sniff(List<BeanTask> tasks) {
return tasks.stream().map(task-> task.level).distinct().toList();
}
Solution 2
as in here shown, without overriding anything in Bean/Object, you can distict objects.
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
public static List<BeanLevel> sniff(List<BeanTask> tasks) {
return tasks.stream().map(task-> task.level).filter(distinctByKey(BeanLevel::getId)).toList();
}