mapTwo = {(1,10.0), (2,20.0)}; ...">

Attach two cards by key

I have two cards:

Map<Integer, String> mapOne = {(1,"a"), (2, "b")}; Map<Integer, Double> mapTwo = {(1,10.0), (2,20.0)}; 

and I want to combine these cards into one using the Integer value, so the result map

 Map<String, Double> mapResult = {("a",10.0), ("b",20.0)}; 

Is there a way to make this easier than iterating over a set of records?

+6
source share
3 answers

Assuming the keys of the two cards are the same and the cards have the same number of records, with Java 8 you can write it on the same line with:

 Map<String, Double> map = mapOne.entrySet().stream() .collect(toMap(e -> e.getValue(), e -> mapTwo.get(e.getKey()))); 

So, you start with the first map and create a new map where the keys are mapOne values ​​and the values ​​are corresponding values ​​in mapTwo.

Technically, this is somewhat equivalent to iterating over the set of records of the first map.

Note: import static java.util.stream.Collectors.toMap; is required import static java.util.stream.Collectors.toMap;

+8
source

It only looks like an iteration:

 @Test public void testCollection() { Map<Integer, String> mapOne = new HashMap<Integer, String>(); mapOne.put(1, "a"); mapOne.put(2, "b"); Map<Integer, Double> mapTwo = new HashMap<Integer, Double>(); mapTwo.put(1, 10.0); mapTwo.put(2, 20.0); Map<String, Double> mapResult = new HashMap<String, Double>(); Set<Integer> keySet = mapOne.keySet(); keySet.retainAll(mapTwo.keySet()); for (Integer value : keySet) { mapResult.put(mapOne.get(value), mapTwo.get(value)); } System.out.println(mapResult); } 
+1
source

If the cards were of the same type, you can use putAll() , but since you are changing pairs of key values, it looks like you have to iterate over each integer, get() from each card, then put(mapOneVal,mapTwoVal)

 for(int i=0;i<max;i++){ String key = mapOne.get(i); Double val = maptwo.get(i); if(key!=null && val!=null) map3.put(key,val); } 
0
source

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


All Articles