Java Collections Framework provides a set of classes and interfaces to represent and manipulate groups of objects. Here’s a Java Collections cheat sheet:
List Interface
ArrayList:
List<String> arrayList = new ArrayList<>();
LinkedList:
List<String> linkedList = new LinkedList<>();
Vector:
List<String> vector = new Vector<>();
Set Interface
HashSet:
Set<String> hashSet = new HashSet<>();
LinkedHashSet:
Set<String> linkedHashSet = new LinkedHashSet<>();
TreeSet:
Set<String> treeSet = new TreeSet<>();
Queue Interface
LinkedList (as Queue):
Queue<String> queue = new LinkedList<>();
PriorityQueue:
Queue<String> priorityQueue = new PriorityQueue<>();
Map Interface
HashMap:
Map<String, Integer> hashMap = new HashMap<>();
LinkedHashMap:
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
TreeMap:
Map<String, Integer> treeMap = new TreeMap<>();
Collections Utility Class
Sorting a List:
Collections.sort(list);
Reverse Order:
Collections.reverse(list);
Shuffling:
Collections.shuffle(list);
Iterating Collections
Using for-each Loop:
for (String item : list) {
// Code
}
Using Iterator:
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
// Code
}
Common Operations
Adding Elements:
list.add("Element");
Removing Elements:
list.remove("Element");
Checking if Empty:
boolean isEmpty = list.isEmpty();
Size of Collection:
int size = list.size();
Arrays to Collections
Array to ArrayList:
List<String> arrayList = Arrays.asList(array);
Synchronization
Creating Synchronized Collection:
Collection<String> synchronizedCollection = Collections.synchronizedCollection(collection);
Generic Wildcards
Upper Bounded Wildcard:
public static double sum(List<? extends Number> list) {
// Code
}
Lower Bounded Wildcard:
public static void addIntegers(List<? super Integer> list) {
// Code
}
Java 8 Stream API
Filtering Elements:
List<String> filteredList = list.stream().filter(s -> s.startsWith("A")).collect(Collectors.toList());
Mapping Elements:
List<Integer> lengths = list.stream().map(String::length).collect(Collectors.toList());
Sorting Elements:
List<String> sortedList = list.stream().sorted().collect(Collectors.toList());
This cheat sheet covers some of the essential concepts and operations related to Java Collections.