0

is it possible to get values of LinkedHashMap by index ?

this is my linkedmap (the reason why i mapped it this way because i need to accumulate the amount and quantity for the duplicated chargeType:

Map<String, ChargeType> chargeTypeCol;

return chargeTypeCol = chargeTypeList
                .stream().collect(Collectors.toMap(ChargeType::getChargeTypeName,
                        Function.identity(),
                        (a, b) -> new ChargeType(a.getId(), b.getChargeTypeName(), a.getAmount() + b.getAmount(), a.getQuantity() + b.getQuantity()),
                        LinkedHashMap::new));

I have 2 of these LinkedHashMap in my logic. What i am trying to do is to compare if the values (getChargeTypeName, getAmount, getQuantity) is equals between the 2 map. Was wondering if there are any possible way to do like

for(int i = 0; i < chargeTypeList.size(); i++){
       for(int j = 0; j < chargeTypeList2.size(); j++){
             if(chargeTypeList.get(i).getChargeTypeName.equalsIgnoreCase(chargeTypeList2.get(j).getChargeTypeName)){
             //todo something here
             }
       }
}
poojay
  • 117
  • 1
  • 2
  • 9
  • You probably need to check this post to know how to iterate Map entries https://stackoverflow.com/questions/46898/how-do-i-efficiently-iterate-over-each-entry-in-a-java-map – Karl Nov 07 '22 at 05:46

1 Answers1

0

You can't really access maps by index, but as it seems your use case is that you need to find pairs from both maps with the same key (chargeTypeName).

One way is using a grouping collector:

var grouped = Stream.of(chargeTypeMap1, chargeTypeMap2)
        .flatMap(c -> c.values().stream())
        .collect(Collectors.groupingBy(ChargeType::getChargeTypeName));

This will return a map which the value is a List with all ChargeTypes with the same chargeTypeName. You can go further and select only the entries which are really pairs:

var result = grouped.values().stream()
        .filter(list -> list.size() == 2)
        .collect(Collectors.toList());

Now we have all the pairs of items with the same chargeTypeName from both maps and can do whatever you need with them.

Vinicius
  • 1,060
  • 1
  • 12
  • 21