Generic Collections

  • Java Collections framework

Collection Iterator

  • List and ArrayList are implementing Collection Interface
...
      List<String> list = new ArrayList<String>();   
      List<String> removeList = new ArrayList<String>();

      // remove from list the colors contained in removeList
      removeColors(list, removeList);

   // remove colors specified in collection2 from collection1
   private static void removeColors(Collection<String> collection1, 
      Collection<String> collection2)
   {
      // get iterator
      Iterator<String> iterator = collection1.iterator(); 

      // loop while collection has items
      while (iterator.hasNext())         
      {
         if (collection2.contains(iterator.next()))
            iterator.remove(); // remove current element
      } 
   } 
...

Reverse iteration:

   // print reversed list
   private static void printReversedList(List<String> list)
   {
      ListIterator<String> iterator = list.listIterator(list.size());

      System.out.printf("%nReversed List:%n");

      // print list in reverse order
      while (iterator.hasPrevious()) 
         System.out.printf("%s ", iterator.previous()); 
   } 

Remove sublist

list.subList(start, end).clear(); // remove items

LinkedList

  • ArrayList use Array behind the scene. Good enough for adding or removing element at the end
  • LinkedList element holds reference to the next element. It is better performance to add or remove elements in the middle of the list.

List <--> Array

  • Arrays.asList return a List that is just a view over the Array, not a copy of the Array
  • You cannot add or remove element in the list returned by Arrays.asList
  • LinkedList.toArray actually create a new copy of Array
   // creates a LinkedList, adds elements and converts to array
   public static void main(String[] args)
   {
      String[] colors = {"black", "blue", "yellow"};
      LinkedList<String> links = new LinkedList<>(Arrays.asList(colors));

      links.addLast("red"); // add as last item
      links.add("pink"); // add to the end
      links.add(3, "green"); // add at 3rd index
      links.addFirst("cyan"); // add as first item      

      // get LinkedList elements as an array     
      colors = links.toArray(new String[links.size()]);

      System.out.println("colors: ");

      for (String color : colors)
         System.out.println(color);
   }  

Sorting

  • The element type that can be sorted must implement Comparable
  • String implements Comparable
  • Otherwise, a Comparator must be used instead
      String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};
      
      // Create and display a list containing the suits array elements
      List<String> list = Arrays.asList(suits); 

      Collections.sort(list); // sort ArrayList

Built-in Comparators

Descending sort is reversing the existing Comparable logic

      // Create and display a list containing the suits array elements
      List<String> list = Arrays.asList(suits); // create List

      // sort in descending order using a comparator
      Collections.sort(list, Collections.reverseOrder()); 

Custom Comparators

      List<Time2> list = new ArrayList<>(); // create List

      // sort in order using a comparator
      Collections.sort(list, new TimeComparator()); 
public class Time2
{
   private int hour; // 0 - 23
   private int minute; // 0 - 59
   private int second; // 0 - 59
  ...
   public String toString()
   {
      return String.format("%d:%02d:%02d %s", 
         ((getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12),
         getMinute(), getSecond(), (getHour() < 12 ? "AM" : "PM"));
   } // end method toString
}
public class TimeComparator implements Comparator<Time2> 
{
   @Override
   public int compare(Time2 time1, Time2 time2)
   {
      int hourDifference = time1.getHour() - time2.getHour();
         
      if (hourDifference != 0) // test the hour first
         return hourDifference; 
         
      int minuteDifference = time1.getMinute() - time2.getMinute(); 
         
      if (minuteDifference != 0) // then test the minute
         return minuteDifference;
         
      int secondDifference = time1.getSecond() - time2.getSecond(); 
      return secondDifference; 
   } 
} // end class TimeComparator
  • compare method
    • return < 0 when first object is less than the second one
    • return > 0 when first object is more than the second one
    • return = 0 when both objects are equal
  • Override method reversed and return the reversed Comparator for descending sort

Collection Methods

reverse, fill, copy, min, and max

      // create and display a List< Character >
      Character[] letters = {'P', 'C', 'M'};
      List<Character> list = Arrays.asList(letters); // get List

      // reverse and display the List<Character>
      Collections.reverse(list); // reverse order the elements

      // create copyList from an array of 3 Characters
      Character[] lettersCopy = new Character[3]; 
      List<Character> copyList = Arrays.asList(lettersCopy); 
      // copy the contents of list into copyList
      Collections.copy(copyList, list);

      // fill list with Rs 
      Collections.fill(list, 'R'); 

      // Print Max and Min
      System.out.printf("%nMax: %s", Collections.max(listRef));
      System.out.printf("  Min: %s%n", Collections.min(listRef));

binarySearch

You must sort the list before using binarySearch

   // perform search and display result
   private static void printSearchResults(
      List<String> list, String key)
   {
      int result = 0;

      result = Collections.binarySearch(list, key);
   }

addAll, frequency, and disjoint

disjoint is true when two lists have nothing in common.

      // initialize list1 and list2
      String[] colors = {"red", "white", "yellow", "blue"};
      List<String> list1 = Arrays.asList(colors);
      ArrayList<String> list2 = new ArrayList<>();

      list2.add("black"); // add "black" to the end of list2
      list2.add("red"); // add "red" to the end of list2
      list2.add("green"); // add "green" to the end of list2

      Collections.addAll(list2, colors); // add colors Strings to list2

      // get frequency of "red"                              
      int frequency = Collections.frequency(list2, "red");  

      // check whether list1 and list2 have elements in common
      boolean disjoint = Collections.disjoint(list1, list2);

HashSet

  • Set is a collection that contain no duplicate elements.
  • No specific order in set.
  • To have an order set, use TreeSet
   // create a Set from a Collection to eliminate duplicates
   private static void printNonDuplicates(Collection<String> values)
   {
      // create a HashSet 
      Set<String> set = new HashSet<>(values);
     ...
   }

SortedSets and TreeSets

      // create TreeSet from array colors
      String[] colors = {"yellow", "green", "black", "tan", "grey",
         "white", "orange", "red", "green"};
      SortedSet<String> tree = new TreeSet<>(Arrays.asList(colors));

      // get headSet based on "orange" (elements before)
      tree.headSet("orange");

      // get tailSet based upon "orange" (elements after, including own)
      tree.tailSet("orange");

      // get first and last elements
      tree.first();
      tree.last();

Map

  • A key-value pair
  • SortedMap is ordered Map by its key

      // create HashMap to store String keys and Integer values
      Map<String, Integer> myMap = new HashMap<>(); 

      // if the map contains the word
      map.containsKey(word)
        
      // get value of the specified key
      map.get(word); // get current count
      
      // Add or update value of the specified key
      map.put(word, count + 1);

      // Get sorted key of map
      Set<String> keys = map.keySet(); // get keys

      // sort keys
      TreeSet<String> sortedKeys = new TreeSet<>(keys);

      // map size
      map.size()
      
      // is the map empty
      map.isEmpty()
No Comments
Back to top