Search code examples
javajava-streamtreemaptreeset

How to map TreeSet value to a TreeMap?


I Have TreeSet set which has some values .
I want to map each element in the set with specific value to be a map using streams .
that for example if the set contains {1,2,3} and the value=5 ;
so I want the map be like this

1->5
2->5
3->5

The problem that I do not know what to write in the map function part

TreeMap<Integer,Integer> map = set.stream().map(x-> ????).collect(Collectors.toCollection(TreeMap:: new )) ;


Solution

  • Don't use map, use Collectors.toMap():

    TreeMap<Integer,Integer> map = 
        set.stream()
           .collect(Collectors.toMap(Function.identity(),i -> 5,(a,b)->a,TreeMap::new));