Skip to content

Instantly share code, notes, and snippets.

@najikadri
Created January 23, 2015 17:57
Show Gist options
  • Save najikadri/a1e9498741a5a70cbecd to your computer and use it in GitHub Desktop.
Save najikadri/a1e9498741a5a70cbecd to your computer and use it in GitHub Desktop.
Code showing the use of collection and iterator in Java
import java.util.*;
/** This code shows the purpose of collection and iterator
* classes in java. This code was made from code from
* the book "Java How To Program - edition 9" from figure 20.2
* @author Naji Kadri
*
* @version 1.0
*/
public class CollectionTest {
public static void main (String args[]) {
String[] colors = {"Red","White","Green","Orange","Blue","Gold"};
List<String> list = new ArrayList<String>();
for (String color: colors) {
list.add(color);
}
String[] removeColors = {"Red","Orange","Gold"};
List<String> removeList = new ArrayList<String>();
for (String color: removeColors) {
removeList.add(color);
}
System.out.println("ArrayList: ");
for (int i=0; i < list.size();i++) {
System.out.printf("%s ",list.get(i));
}
removeColors (list,removeList);
System.out.println("\nArrayList after removing colors");
for (String color: list) {
System.out.printf("%s ", color);
}
}
public static void removeColors (Collection<String> collection1, Collection<String> collection2) {
Iterator<String> iterator = collection1.iterator();
while (iterator.hasNext()) {
if (collection2.contains(iterator.next())) {
iterator.remove();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment