How to create a map with Java stream API using a value outside the stream?

后端 未结 3 462
灰色年华
灰色年华 2020-12-18 19:48

I want to init a Map and want to always put the same BigDecimal value from outside of the stream.

BigDeci         


        
相关标签:
3条回答
  • 2020-12-18 19:53

    As already said in the other answers, you need to specify a function which maps each element to the fixed value like element -> samePrice.

    As an addition, if you want to specifically fill a ConcurrentHashMap, there is a neat feature that doesn’t need a stream operation at all:

    ConcurrentHashMap<String,BigDecimal> map = new ConcurrentHashMap<>();
    map.keySet(samePrice).addAll(set);
    

    Unfortunately, there is no such operation for arbitrary Maps.

    0 讨论(0)
  • 2020-12-18 20:09

    The second argument (like the first one) of toMap(keyMapper, valueMapper) is a function that takes the stream element and returns the value of the map.

    In this case, you want to ignore it so you can have:

    set.stream().collect(Collectors.toMap(Function.identity(), e -> samePrice));
    

    Note that your second attempt wouldn't work for the same reason.

    0 讨论(0)
  • 2020-12-18 20:13

    Collectors#toMap expects two Functions

    set.stream().collect(Collectors.toMap(Function.identity(), x -> samePrice));
    

    You can find nearly the same example within the JavaDoc

     Map<Student, Double> studentToGPA
         students.stream().collect(toMap(Functions.identity(),
                                         student -> computeGPA(student)));
    
    0 讨论(0)
提交回复
热议问题