简体   繁体   中英

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

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();
    }
}

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));
            }
        }
    }

查看如何比较两个ArrayList <List <String >>像一个二维数组一样考虑它,并将列表A的每个元素与列表B.get(1),列表B.get(2)等中的每个元素进行比较。

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM