Search code examples
javacollectorsfunctional-interface

How to take Generic Function<T,R> input parameter for mapper


I have a list of members which I need to map for different keys for different usage and I want to turn map method to takes keyMapper as an input parameter for Collectors.toMap() method.

public Map<String, Member> getMemberMap(){
    Collections.unmodifiableMap(getMemberList().stream.collect(Collectors.toMap(Member::getName, Function.identity())));
}

How can I turn this method take a Function<T,R> key mapper for different fields of Member to map.

Such as getMemberMap({id}) or getMemberMap({code})


Solution

  • First the method needs to change to accept the function. I'm using wildcard here for more flexibility:

    public <R> Map<R, Member> getMemberMap(Function<? super Member, ? extends R> mapper) { 
        return getMemberList().stream()
                .collect(Collectors.toUnmodifiableMap(mapper, Function.identity()));
    }
    

    You can then call it as needed:

    getMemberMap(Member::getId);
    getMemberMap(Member::getCode);
    getMemberMap(Member::getName);
    getMemberMap(member -> member.getName().toUpperCase());