How to collect a stream into a TreeMap

Viewed 17026

I know this is a noob a question, but I couldn't find a simpe answer anywhere else. Question is: I need to write a method that returns a SortedMap, so a tree map should work just fine. I have a HashMap< String, Skill>, the Skill class has both the methods getName and getNumApplicants and I need to return a SortedMap<String, Long>, with the name of the skill as a key and the number of applicants as value. This is where I stand:

private Map<String,Skill> skillMap = new HashMap<>();

public SortedMap<String, Long> skill_nApplicants() {

    return skillMap.values().stream().collect(...);
}

This is the Skill class

public class Skill {

    private String name;
    private List <Position> reqPosition = new ArrayList<>();
    private Long numApplicants;

    public void plusOneApplicant() {
        this.numApplicants++;
    }

    public Long getNumApplicants() {
        return numApplicants;
    }
    public Skill(String name) {
        super();
        this.name = name;
        this.numApplicants = 0L;
    }
    public String getName() {
        return name;
        }

    public List<Position> getPositions() {
        return reqPosition;
        }
    public void addReqPosition(Position p) {
        this.reqPosition.add(p);
        return;
    }
}

I know this should be very easy, I just have a very hard time in understanding this all thing.

3 Answers

Don't collect the data to a HashMap first, then convert to a TreeMap. Collect the data directly to a TreeMap by using the overloaded toMap(keyMapper, valueMapper, mergeFunction, mapSupplier) method that allows you to specify which Map to create (4th parameter).

public SortedMap<String, Long> skill_nApplicants() {
    return skillMap.values().stream().collect(Collectors.toMap(
            Skill::getName,
            Skill::getNumApplicants,
            Math::addExact, // only called if duplicate names can occur
            TreeMap::new
    ));
}

This is how you can do it

public SortedMap<String, Long> skill_nApplicants(Map<String, Skill> skillMap) {
    Map<String, Long> result = skillMap.values().stream().collect(Collectors.toMap(Skill::getName, Skill::getNumApplicants));
    return new TreeMap<>(result);
}

If you don't have any value which will be mapped to the same key as another value, then you can avoid to use a Collector at all (and thus you don't need to think about a merge function).

All you need to do is to simply add each skill to the map with a forEach:

public SortedMap<String, Long> skill_nApplicants() {
    Map<String, Long> result = new TreeMap<>();
    
    skillMap.values()
        .forEach((skill) -> result.put(skill.getName(), skill.getNumApplicants());
        
    return result;
}

You can wrap result with Collections.unmodifiableSortedMap if you want to return an unmodifiable map.

Related