-1

When using streams, is there any smarter way to create a distinct list without using new ArrayList() and return lst lines?

public static List<BeanLevel> sniff(List<BeanTask> tasks) {
    List<BeanLevel> lst = new ArrayList();
    tasks.stream().map(task-> task.level).forEach(level-> {
        if (lst.stream().filter(distinctLevel-> level.id == distinctLevel.id).findAny().isPresent()) {
            return;
        }
        lst.add(level);
    });
    return lst;
}

1 Answers1

0

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();
}
  • 1
    Overriding equals without overriding hashcode is bad idea, you will break the contract that 2 objects, which are considered equal must produce the same hashcode. – Chaosfire Aug 29 '22 at 07:00
  • @Chaosfire U r right https://www.baeldung.com/java-equals-hashcode-contracts explains why. – Tugalsan Karabacak Aug 29 '22 at 07:12