The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases.
Collection, and therefore sits at the top of its own tree. What is the name
of this interface? Map<E> syntax, which tells you that it is
generic. When you declare a Collection instance, what is
the advantage of specifying the type of objects that it will contain? Set
Collection
List
Queue
Map
Deque
List.
List using streams, the enhanced for statement, or iterators.
import java.util.*;
public class Ran {
public static void main(String[] args) {
// Get and shuffle the list of arguments
List<String> argList = Arrays.asList(args);
Collections.shuffle(argList);
// Print out the elements using JDK 8 Streams
argList.stream()
.forEach(e->System.out.format("%s ",e));
// Print out the elements using for-each
for (String arg: argList) {
System.out.format("%s ", arg);
}
System.out.println();
}
}
FindDupsexample
and modify it to use a SortedSet instead of a Set. Specify a Comparator so that case is ignored when sorting and identifying set elements.
import java.util.*;
public class FindDups {
public static void main(String[] args) {
Set<String> s = new HashSet<String>();
for (String a : args)
s.add(a);
System.out.println(s.size() + " distinct words: " + s);
}
}
List<String> and applies
String.trim to each element.
for statement does not allow you to modify the List. Using an instance of the Iterator class allows you to delete elements, but not replace an existing element or add a new one. That leaves ListIterator:
import java.util.*;
public class ListTrim {
static void listTrim(List<String> strings) {
for (ListIterator<String> lit = strings.listIterator(); lit.hasNext(); ) {
lit.set(lit.next().trim());
}
}
public static void main(String[] args) {
List<String> l = Arrays.asList(" red ", " white ", " blue ");
listTrim(l);
for (String s : l) {
System.out.format("\"%s\"%n", s);
}
}
}
Set, List, Queue, and Map.
For each of the following four assignments, specify which of the four core
interfaces is best-suited, and explain how to use it to implement the assignment. List. Choose a random employee by picking a number between 0 and size()-1.Set. Collections that implement this interface don't allow the same element to be entered more than once.Map, where the keys are first names, and each value is a count of the number of employees with that first name.Queue. Invoke add() to add employees to the waiting list, and remove() to remove them.