0% found this document useful (0 votes)
17 views4 pages

Collection

This document is a comprehensive cheat sheet for Java Collections, covering import statements, creation of various collection types (ArrayList, HashSet, HashMap, etc.), and basic operations for each type. It includes details on iterating, sorting, and converting between collections, as well as handling capacity and thread-safe collections. Additionally, it provides utility methods for managing collections and operations specific to sets and maps.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views4 pages

Collection

This document is a comprehensive cheat sheet for Java Collections, covering import statements, creation of various collection types (ArrayList, HashSet, HashMap, etc.), and basic operations for each type. It includes details on iterating, sorting, and converting between collections, as well as handling capacity and thread-safe collections. Additionally, it provides utility methods for managing collections and operations specific to sets and maps.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

------------------------------------------------------------

Java Collections Cheat Sheet


------------------------------------------------------------

1. Import Statements
------------------------------------------------------------
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeMap;
import java.util.Collections;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

------------------------------------------------------------

2. Creating Collections
------------------------------------------------------------
ArrayList<String> list = new ArrayList<>();
ArrayList<Integer> numbers = new ArrayList<>();

HashSet<String> set = new HashSet<>();


LinkedHashSet<String> linkedSet = new LinkedHashSet<>();
TreeSet<String> treeSet = new TreeSet<>();

HashMap<String, Integer> map = new HashMap<>();


LinkedHashMap<String, Integer> linkedMap = new LinkedHashMap<>();
TreeMap<String, Integer> treeMap = new TreeMap<>();

------------------------------------------------------------

3. Basic Operations for ArrayList


------------------------------------------------------------
list.add("Apple"); // Add element
list.add(1, "Banana"); // Add at index
list.get(0); // Get element at index
list.set(0, "Mango"); // Replace element at index
list.remove(1); // Remove element at index
list.remove("Apple"); // Remove by value
list.clear(); // Remove all elements
list.size(); // Get number of elements
list.isEmpty(); // Check if list is empty
list.contains("Mango"); // Check if value exists
list.indexOf("Mango"); // Get index of value
list.lastIndexOf("Mango"); // Get last index of value
list.subList(1, 3); // Get sublist between indexes
list.toArray(); // Convert list to array

------------------------------------------------------------

4. Iterating Over ArrayList


------------------------------------------------------------
// Using for loop
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}

// Using for-each
for (String item : list) {
System.out.println(item);
}

------------------------------------------------------------

5. Sorting for ArrayList


------------------------------------------------------------
import java.util.Collections;

Collections.sort(list); // Sort in ascending order


Collections.sort(list, Collections.reverseOrder()); // Sort in descending order
Collections.reverse(list); // Reverse order

------------------------------------------------------------

6. Conversion Between Array and ArrayList


------------------------------------------------------------
// Array to ArrayList
String[] arr = {"A", "B", "C"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(arr));

// ArrayList to Array
String[] array = list.toArray(new String[0]);

------------------------------------------------------------

7. Capacity Handling for ArrayList


------------------------------------------------------------
// Default capacity is 10
// Use ensureCapacity to increase if needed
list.ensureCapacity(100);

------------------------------------------------------------

8. ArrayList vs Array
------------------------------------------------------------
Array - Fixed size, faster for indexed access
ArrayList - Dynamic size, more flexible and feature-rich

Example:
int[] arr = new int[5]; // Fixed size
ArrayList<Integer> list = new ArrayList<>(); // Grows as needed

------------------------------------------------------------

9. Set Operations (HashSet, LinkedHashSet, TreeSet)


------------------------------------------------------------
set.add(10); // Add element
set.remove(10); // Remove element
set.size(); // Get number of elements
set.contains(10); // Check if value exists
set.isEmpty(); // Check if set is empty
set.iterator(); // Get iterator to traverse set
set.addAll(otherSet); // Add all elements from another set
set.removeAll(otherSet); // Remove all elements of another set from current
set
set.retainAll(otherSet); // Retain only elements present in both sets
set.containsAll(otherSet); // Check if set contains all elements of another
set

List<Integer> sortedList = new ArrayList<>(set); // Convert Set to List


Collections.sort(sortedList); // Sort List

------------------------------------------------------------

10. Map Operations (HashMap, LinkedHashMap, TreeMap)


------------------------------------------------------------
map.put("A", 1); // Add key-value pair
map.get("A"); // Get value by key
map.remove("A"); // Remove by key
map.containsKey("A"); // Check if key exists
map.containsValue(1); // Check if value exists
map.size(); // Get number of key-value pairs
map.keySet(); // Get set of keys
map.values(); // Get collection of values
map.entrySet(); // Get set of key-value pairs
map.replace("A", 2); // Replace value for a specific key
map.putIfAbsent("B", 3); // Add key-value if key does not exist
map.remove("B", 3); // Remove key-value pair if value matches

------------------------------------------------------------

11. Iterating Over Map


------------------------------------------------------------
// Using for-each to iterate over key-value pairs
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}

// Using Iterator
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println(entry.getKey() + " = " + entry.getValue());
}

------------------------------------------------------------

12. Sorting Map (by Key or Value)


------------------------------------------------------------
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;

Map<String, Integer> sortedByKey = new TreeMap<>(map); // Sort map by key


System.out.println(sortedByKey); // Prints map sorted by
keys

// Sort Map by value using a comparator


List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Map.Entry.comparingByValue()); // Sort by values in ascending order

------------------------------------------------------------
13. Handling Collections
------------------------------------------------------------
// Creating an unmodifiable collection (immutable)
List<String> unmodifiableList = Collections.unmodifiableList(list);
Set<String> unmodifiableSet = Collections.unmodifiableSet(set);
Map<String, Integer> unmodifiableMap = Collections.unmodifiableMap(map);

------------------------------------------------------------

14. Working with Collections Utility Methods


------------------------------------------------------------
import java.util.Collections;

// Find max element in List


String maxValue = Collections.max(list);

// Find min element in List


String minValue = Collections.min(list);

// Shuffle elements in List


Collections.shuffle(list);

// Reverse the order of elements in List


Collections.reverse(list);

// Swap two elements in List


Collections.swap(list, 0, 1);

// Fill List with a particular element


Collections.fill(list, "Default Value");

// Replace all occurrences of a specific value in List


Collections.replaceAll(list, "Old", "New");

// List to Set (removes duplicates)


Set<String> setFromList = new HashSet<>(list);

// Set to List
List<Integer> listFromSet = new ArrayList<>(set);

// List to Map (custom mapping needed)


Map<Integer, String> mapFromList = list.stream()
.collect(Collectors.toMap(String::length, Function.identity()));

// Map to List (values only)


List<Integer> valuesList = new ArrayList<>(map.values());

------------------------------------------------------------

15. Thread-Safe Collections


------------------------------------------------------------
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

// Create thread-safe collections


List<String> threadSafeList = new CopyOnWriteArrayList<>();
Set<Integer> threadSafeSet = new CopyOnWriteArraySet<>();

------------------------------------------------------------

You might also like