Q:

Java - Iterate two lists, compare then add to another list

I have three lists: listA, listB, listC.
listA        listB
1,a,tf       b,true
2,b,tf       a,false
3,c,tf       c,true

and I would like to have listC to be listA + listB in order of listA (replacing listA's tf with listB's true/false).
listC
1,a,false
2,b,true
3,c,true

Here's my code
Iterator a= listA.iterator();
Iterator b= listB.iterator();
    while(a.hasNext()){
        while(b.hasNext()){
            if(String.valueOf(a.next()).split(",")[1].equals(String.valueOf(b.next()).split(",")[0])){
                    listC.add(String.valueOf(a.next()).replaceAll("tf", String.valueOf(b.next()).split(",")[1]));
            }
        }
    }

With individual iterator-while for listA and listB being split and indexed, it works fine, but when I run the code above, the program just freezes. Any thoughts?

A:

You're really not far off. Iterators can be confusing and so I tend to avoid them.
I can't really see where the infinite loop is in your code - I expected a NullPointerException because you're calling a.next() and b.next() multiple times.
If you change your code to remove the iterators, it works fine:
List<String> listA = Arrays.asList("1,a,tf", "2,b,tf", "3,c,tf");
List<String> listB = Arrays.asList("b,true", "a,false", "c,true");
List<String> listC = new ArrayList<>();

for(String a : listA)
{
    for (String b : listB)
    {
        if (String.valueOf(a).split(",")[1].equals( String.valueOf(b).split(",")[0] ) )
        {
            listC.add(String.valueOf(a).replaceAll("tf", String.valueOf(b).split(",")[1]));
        }
    }
}

System.out.println(listC.toString());

