Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-Stream, toMap with duplicate keys

So there might be one abc for several payments, now I have:

//find abc id for each payment id
Map<Long, Integer> abcIdToPmtId = paymentController.findPaymentsByIds(pmtIds)
          .stream()
          .collect(Collectors.toMap(Payment::getAbcId, Payment::getPaymentId));

But then I reallize this could have duplicate keys, so I want it to return a

Map<Long, List<Integer>> abcIdToPmtIds 

which an entry will contain one abc and his several payments.

I know I might can use groupingBy but then I think I can only get Map<Long, List<Payments>> .

like image 753
KKlalala Avatar asked Feb 06 '18 18:02

KKlalala


People also ask

Do Hashmaps allow for duplicates?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

How do I store duplicate keys on a map?

You can use a TreeMap with a custom Comparator in order to treat each key as unequal to the others. It would also preserve the insertion order in your map, just like a LinkedHashMap. So, the net result would be like a LinkedHashMap which allows duplicate keys!

How do you find duplicates in a list using streams?

Get the stream of elements in which the duplicates are to be found. For each element in the stream, count the frequency of each element, using Collections. frequency() method. Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.

Can TreeMap have duplicate keys?

A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.


1 Answers

Use the other groupingBy overload.

paymentController.findPaymentsByIds(pmtIds)
      .stream()
      .collect(
          groupingBy(Payment::getAbcId, mapping(Payment::getPaymentId, toList());
like image 138
Louis Wasserman Avatar answered Nov 09 '22 03:11

Louis Wasserman