Confuses Java8 Collectors.toMap

I have a collection that looks like below, and I want to filter everything except dates that are not month ends.

2010-01-01=2100.00, 
2010-01-31=2108.74, 
2010-02-01=2208.74, 
2010-02-28=2217.92, 
2010-03-01=2317.92, 
2010-03-31=2327.57, 
2010-04-01=2427.57, 
2010-04-30=2437.67, 
2010-05-01=2537.67, 
2010-05-31=2548.22, 
2010-06-01=2648.22, 
2010-06-30=2659.24, 
2010-07-01=2759.24, 
2010-07-31=2770.72, 
2010-08-01=2870.72, 
2010-08-31=2882.66, 
2010-09-01=2982.66, 
2010-09-30=2995.07, 
2010-10-01=3095.07, 
2010-10-31=3107.94, 
2010-11-01=3207.94, 
2010-11-30=3221.29

I have the following filtering criteria. frequency.getEndreturns the LocalDatecorresponding end of the month for the given LocalDate.

.filter(p -> frequency.getEnd(p.getKey()) == p.getKey())

So now I think I need to convert this filtered stream back to a map. And I think I use a collector for this. So I add:

.collect(Collectors.toMap(/* HUH? */));

But I do not know what to do with Collectors.toMap. Reading examples leave me confused. Here is my current code that is clearly not working.

TreeMap<LocalDate, BigDecimal> values = values.entrySet()
                                              .stream()
                                              .filter(p -> frequency.getEnd(p.getKey()) == p.getKey())
                                              .collect(Collectors.toMap(/* HUH? */));
+4
source share
4 answers

, , ​​ Stream API:

values.keySet().removeIf(k -> !frequency.getEnd(k).equals(k));
+3

: , Stream<Map.Entry<LocalDate, BigDecimal>>, TreeMap<LocalDate, BigDecimal>.

, , Collectors.toMap. , , 3 Collectors.toMap, :

toMap, , Map a TreeMap. , :

  • keyMapper: . Stream<Map.Entry<LocalDate, BigDecimal>>, Stream Map.Entry<LocalDate, BigDecimal>. Map.Entry<LocalDate, BigDecimal> e. , e.getKey(), .. LocalDate, . -: e -> e.getKey(). Map.Entry::getKey, lambdas, .
  • valueMapper: , , e.getValue(), .. BigDecimal, . , e -> e.getValue().
  • mergeFunction: . , (.. LocalDate) . ? , : , , . , , . (v1, v2) -> { throw new SomeException(); }. , . , JDK , SomeException IllegalStateException.
  • mapSupplier: , TreeMap. . , () -> new TreeMap<>(). , TreeMap::new.

, ( , , , ):

Collectors.toMap(
       e -> e.getKey(),    // Map.Entry::getKey
       e -> e.getValue(),  // Map.Entry::getValue
       (v1, v2) -> { throw new IllegalStateException(); },
       () -> new TreeMap<>())  // TreeMap::new
)
+15

Map.Entry, toMap() , :

Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)

, TreeMap. :

Collectors.toMap(Entry::getKey,
                 Entry::getValue,
                 (v1,v2) -> { throw new IllegalStateException("Duplicate key"); },
                 TreeMap::new)
+2

toMap : - , - . , .

I think you need to do something like this:

Collectors.toMap(p -> p.getKey(), p -> p.getValue())
0
source

Source: https://habr.com/ru/post/1615988/


All Articles