Web Development, SEO, Social Media, Software & Database Development
Java ArrayList using Iterator
This tutorial uses iterator to compare 2 arraylists and removes duplicate from list1 that are found is list2.
------------------------------CODE-------------------------------------------------------------
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;
import java.util.Iterator;
/// CREATE 2 ARRAYLISTS.
/// POPULATE LISTS WITH STRINGS.
/// CREATE METHOD THAT COMPARES LIST1 AND LIST2 AND REMOVES
/// ANY DUPLICATES IN LIST1 THAT MAY BE FOUND IN LIST 2
class Colls
{
public static void main(String args[])
{
List <String> list1 = new ArrayList<String>();
List <String> list2 = new ArrayList<String>();
//////////////////
//POPULATE LISTS//
//////////////////
list1.add("Cow");
list1.add("Pig");
list1.add("Sheep");
list1.add("Cat");
list2.add("Cow");
list2.add("Wolf");
list2.add("Fox");
list2.add("Hen");
//DISPLAY LIST1 AND LIST2 DATA
System.out.println("LIST 1 DATA : "+list1);
System.out.println("LIST 2 DATA : "+list2);
//////////////////////////////////////////////
//CALL METHOD EDIT LIST TO REMOVE DUPLICATES//
//////////////////////////////////////////////
editList(list1,list2);
System.out.println();
//DISPLAY LIST1 AND LIST2 DATA AFTER DUPLICATES DELETED
System.out.println("LIST 1 DATA : "+list1);
System.out.println("LIST 2 DATA : "+list2);
}
public static void editList(Collection <String> l1, Collection <String> l2)
{
////////////////////////////////////////////////////////////////
// CREATE ITERATOR SO WE CAN LOOP THOUGH ITEM TO ITEM OF LIST1//
////////////////////////////////////////////////////////////////
Iterator <String> it = l1.iterator();
while(it.hasNext())
{
if(l2.contains(it.next()))
it.remove();
}
}
}
-------------------OUTPUT ---------------------------------------------------
LIST 1 DATA : [Cow, Pig, Sheep, Cat]
LIST 2 DATA : [Cow, Wolf, Fox, Hen]
LIST 1 DATA : [Pig, Sheep, Cat]
LIST 2 DATA : [Cow, Wolf, Fox, Hen]
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment