Loop a list by generic Iterator

 
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class OysterMonths {
  Collection<String> safeMonths;

  public Collection<String> filter(Collection<String> c) {

    Collection<String> filteredCollection = new ArrayList<String>();

    for (Iterator<String> i = c.iterator(); i.hasNext();) {
      String s = i.next();
      if (condition(s)) {
        filteredCollection.add(s);
      }
    }
    return filteredCollection;
  }

  public boolean condition(String s) {
    return s.contains("r");
  }

  public static void main(String[] args) {
    OysterMonths om = new OysterMonths();
    DateFormatSymbols dfs = new DateFormatSymbols();
    String[] monthArray = dfs.getMonths();
    Collection<String> months = Arrays.asList(monthArray);
    om.safeMonths = om.filter(months);
    System.out.println("The following months are safe for oysters:");
    System.out.println(om.safeMonths);
  }
}
  
Home 
  Java Book 
    Runnable examples  

Collection List:
  1. Create a list from an array
  2. Add element to a list at specified index
  3. Append one list to another list
  4. Insert a list at Specified Index
  5. Compare two List objects
  6. Convert Collection to List
  7. Convert a Queue to a List
  8. Convert List to array
  9. Convert List to a Set
  10. Copy List to Vector
  11. Copy one List to Another List
  12. Fill all elements in a list
  13. Fill n Copies of Specified Object
  14. Find maximum element in a List
  15. Find Minimum element in a List
  16. Get element by index
  17. Get Enumeration over List
  18. Get Synchronized List from a List
  19. Get Sub List
  20. Loop a list by Iterator
  21. Loop a list by generic Iterator
  22. Loop a list with using ListIterator
  23. Loop through a ist in reverse direction using ListIterator
  24. Remove an element by value and by index from List
  25. Remove all elements from a List
  26. Remove duplicate items from a List
  27. Remove item from a List while looping
  28. Remove range of elements from a List
  29. Remove user object from a list
  30. Replace an Element of List
  31. Replace all occurrences of specified element in a List
  32. Replace an element in a List using ListIterator
  33. Reverse a List
  34. Reverse order of all elements in a List
  35. Rotate elements of a list
  36. Search a List for an item with contains method
  37. Search elements of a List
  38. Binary Search a Sorted List
  39. Binary Search for a non-existent element in a List
  40. Set to change(replace) the value in a list
  41. Shuffle elements in a List
  42. Shuffle(repeatable) a List
  43. Sort a list
  44. Sort a List in descending order using comparator
  45. Swap elements of List