javasetjava-streamtreeset

@Override TreeSet add methode for add juste 4 elements (on Java)


I have a List, i stream it to an Treemap with key and values where the values are a TreeSet and for this TreeSet I what juste add 4 first elements to the Treeset stream not all element

Map<Integer, Set<Person>> stream_exo = ListOfPerson.stream()
                .collect(
                        Collectors.groupingBy(
                                p -> p.getYear(), 
                                TreeMap::new, Collectors.toCollection(TreeSet2::New)));

here is the treeSet Class of java :

public class TreeSet<E> extends AbstractSet<E>
                   implements NavigableSet<E>, Cloneable, java.io.Serializable {

    private static final Object PRESENT = new Object();
    
    private transient TreeMap<E,Object> internalMap;
    
    public boolean add(E e) {
        return this.internalMap.put(e, PRESENT)==null;
    }
}

I want to costume function (add) for TreeSet to add just 4 elements to the TreeSet, someone can ask me how we can do that ?


Solution

  • this has nothing to do with streams...just plain inheritance.

    create a new class "MaxFourTreeSet" which "extends TreeSet" and override the add() function to add your condition. then, in your stream use MaxFourTreeSet::new instead of TreeSet::new. that's all.

    public class MaxFourTreeSet<E> extends TreeSet<E> {
    
    @Override
    public boolean add(E e) {
        if (this.size() <= 4) {
            return super.add(e);
        } 
        return false;
     } 
    }
    

    (code not accurate)