OO Programming with Java


Lists & Iterators

  1. java.util offers most of the algorithms to deal with collections.
    As an example, the following code shows how to sort lists:
List<String> lst = Arrays.asList("This","is","an","illustration"); 
  // Notice to capability to have 'variable' arguments
Collections.sort(lst);
System.out.println(lst); // [This, an, illustration, is]

The code use "lexical order" but other orders can be specified by the way of comparator objects:

Comparator<String> infStr = new Comparator<String>() { // Interface instanciation
  public int compare(String o1, String o2) {
    return o2.compareTo(o1);
  }};
lst.sort(infStr);
System.out.println( lst ); // [is, illustration, an, This]

go further


Try it yourself with jshell !


8 - 13