0

I have two LinkedHashMap<String, MyType> where keys can be common (say key from first map can be "key" and key from second map can be also "key". I need to compare this two maps and when keys are equal I want create new object where firsMapEntry.getValue() secondMapEntry.getValue() are attributes of new object [ new MyObject(firsMapEntry.getValue(), secondMapEntry.getValue()) ]. Maps are in Collection so I iterate through collections.

Here's my source:

firstIterator = firsCollection.iterator();
secondIterator = secondCollection.iterator();

    while (firstIterator.hasNext() && secondIterator.hasNext()) {
        Map<String, MyType1> firsMap = firstIterator.next();
        Map<String, List<MyType2>> secondMap = secondIterator
                .next();

        firstMapIterator = firstMap.entrySet().iterator();
        secondMapIterator = secondMap.entrySet().iterator();

        while (firstMapIterator.hasNext() && secondMapIterator.hasNext()) {
            Map.Entry<String, MyType1> firstEntry = ((Map.Entry<String, MyType1>) firstMapIterator.next());
            Map.Entry<String, List<MyType2>> secondEntry = ((Map.Entry<String, List<MyType2>>) secondMapIterator.next());


           // Here I was trying to compare keys but unsuccessfuly

          // if keys are equal create new object

        My Object object = new MyObject(firsEntry.getValue(),
                    secondEntry.getValue());
                      Map<String, MyObject> map = new LinkedHashMap<String,MyObject(); map.put("key", object);

        }
    }

Return type of method is List<Map<String, MyObject>>. I don't know if my method is effecient, but how to compare two keys and create new object from values. Every help will be appreciated. Thank you.

Martin
  • 2,146
  • 4
  • 21
  • 32
  • Where are you comparing the keys in your above code? Have you removed that piece and replaced with the comments? – Swapnil Jan 06 '13 at 18:30
  • Yes where are comments, there I want compare keys. I had sth. like if ( firstkey.equals(secondKey) { ... but as result a I got always only one Map – Martin Jan 06 '13 at 18:31
  • What if you have map entries `1, 2` in the first map and `2, 1` in the second? You use `LinkedHashMap` so it appears that insertion order is significant to you; hence the question – fge Jan 06 '13 at 18:41

1 Answers1

1

Map.Entry has a method called getKey() , use this to get the key.
Since your key is a String use , Object.equals() to compare them , do not use '==' ,so:

    if(firstEntry .getKey().equals(secondEntry .getKey())){
    //they are equal
    }
else{
    //they are different
    }
Community
  • 1
  • 1
wtsang02
  • 18,603
  • 10
  • 49
  • 67