0
List<String> a = new ArrayList();
a.add("one");
a.add("two");
a.add("one");
Map<Integer,List<String>> map = new HashMap();
map.put(1,list1);
map.put(1,list2);

How can I compare list a with list1 and list2?

  • 1
    you put two objects to the map for the same key. This does not make sense. – Alexey R. Jun 4 '18 at 9:53
  • This seems more of a general Java question. Is this for part of a unit test? – corsiKa Jun 4 '18 at 17:19
2

This is the example (I have fixed your map so that the construction does make sense)

@Test
public void testListCompare(){
    List<String> a = new ArrayList();
    a.add("one");
    a.add("two");
    a.add("one");
    List<String> list1 = new ArrayList();
    list1.add("one");
    list1.add("two");
    list1.add("one");
    List<String> list2 = new ArrayList();
    list2.add("two");
    list2.add("one");
    list2.add("one");
    Map<Integer,List<String>> map = new HashMap();
    map.put(1,list1);
    map.put(2,list2);

    for(Map.Entry<Integer, List<String>> entry: map.entrySet()){
        System.out.println(a.equals(entry.getValue()));
    }
}

Since you're using ArrayList it extends AbstractList that has equals() method overridden to properly compare the lists.

Otherwise if you implement your own List, you can use something like this:

public boolean ifListsAreEqual(List base, List candidate){
    if(base.size() != candidate.size()){
        return false;
    }
    for(int i = 0; i < base.size(); i++){
        if(!base.get(i).equals(candidate.get(i))){
            return false;
        }
    }
    return true;
}     
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.