Lesson 29 of 36Article17 min
List Sorting, Set, HashSet, TreeSet & LinkedHashSet
Collections.sort(list) or list.sort(null) for natural order. Custom order with Comparator.
List Sorting
Collections.sort(list) or list.sort(null) for natural order. Custom order with Comparator.
Strings sort alphabetically. Numbers sort numerically.
Real-life example: Sorting a class by marks is Comparator — you define "higher marks first" rule.
Sort list
import java.util.*;
List<Integer> nums = new ArrayList<>(List.of(30, 10, 20));
Collections.sort(nums);
System.out.println(nums); // [10, 20, 30]
nums.sort((a, b) -> b - a); // descending
System.out.println(nums); // [30, 20, 10]Set, HashSet, TreeSet & LinkedHashSet
Set stores unique values. HashSet — fast, no order. LinkedHashSet — insertion order. TreeSet — sorted order.
add duplicate returns false — Set ignores duplicate.
Real-life example: HashSet is a bag of unique marbles — shake it, order random. TreeSet is marbles sorted by size automatically.
Set implementations
Set<String> hash = new HashSet<>();
hash.add("java");
hash.add("java"); // ignored
System.out.println(hash.size()); // 1
Set<String> tree = new TreeSet<>();
tree.add("banana");
tree.add("apple");
System.out.println(tree); // [apple, banana]