Mike
Mike

Reputation: 919

Java: How do I compare a List<String> with List<List<String>>?

There is an ArrayList1 and a List2 containing several arraylists in it.

I want to compare the contents in arraylist1 with all the arraylists(in List2) and throw out the records from List2 which are not equal to arraylist1.

There are couple of questions similar to this one, but I could't understand it clearly. Please help.

Thanks, Mike

Upvotes: 0

Views: 150

Answers (4)

Klemens Morbe
Klemens Morbe

Reputation: 653

I guess you want something like that:

    List<List<String>> listlist = new ArrayList<List<String>>();
    List<String> list = new ArrayList<String>();

    // some example input here
    list.add("A");
    list.add("B");
    list.add("C");

    listlist.add(list);

    for (List<String> l : listlist) {
        for(String s : l) {
            if (list.contains(s)) {
                System.out.println(s + " is at position " + list.indexOf(s));
            }
        }
    }

Upvotes: 2

TheBetaProgrammer
TheBetaProgrammer

Reputation: 104

Sounds like a homework question so here is the logic

input: List of Arrays, Array
output: List

List Compiar getList(L, A):
|   newL <- new List
|   for each Array a in L do
|   |   for int i <- 0 to A.size()
|   |   |   Array n = new Array
|   |   |   for int j <- 0 to a.size()
|   |   |   |   if  compairitor(A.get(i), a.get(j)) = 0 // compairitor is used to compair values
|   |   |   |   |    n.add(a.get(j)
|   |   |   |   end-if
|   |   |   end-for
|   |   |   newL.add(n)
|   |   end-for
|   end-for-each    
|     return newL
end 

Use this method to replase the old list ex List old = getList(L, Comparison array)

Upvotes: 1

dna8675
dna8675

Reputation: 677

Check out How to compare two ArrayList<List<String>> Think about it like a two dimensional array and compare each element of list A to each element in list B.get(1), list B.get(2), etc.

Upvotes: 1

Rogue
Rogue

Reputation: 11483

Depending on how you want to implement, iterate:

List<String> yourSingleList = new ArrayList<>();
for (List<String> list : yourListOfLists) {
    //remove entries
    list.retainAll(yourSingleList);
    //or remove matching entities
    list.removeAll(yourSingleList);
}

Or use an iterator to compare entirely:

List<String> yourSingleList = new ArrayList<>();
Iterator<List<String>> lists = yourListOfLists.iterator();
while (lists.hasNext()) {
    if (!lists.next().equals(yourSingleList) {
        lists.remove();
    }
}

Upvotes: 1

Related Questions