Collection
public class CollectionDemo {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();
collection.add("Apple");
collection.add("Banana");
collection.add("Cherry");
System.out.println("Collection after adding elements: " +
collection);
Collection<String> moreFruits = Arrays.asList("Date",
"Elderberry", "Fig");
collection.addAll(moreFruits);
System.out.println("Collection after addAll(): " +
collection);
System.out.println("Collection after equal(): " + c
ollection.equals(morefruits));
collection.remove("Banana");
System.out.println("Collection after remove('Banana'): "
+ collection);
Collection<String> toRemove = Arrays.asList("Apple",
"Cherry");
collection.removeAll(toRemove);
System.out.println("Collection after removeAll(): " +
collection);
System.out.println("Contains 'Date'?: " +
collection.contains("Date"));
Collection<String> checkFruits = Arrays.asList("Date",
"Elderberry");
System.out.println("Contains all checkFruits?: " +
collection.containsAll(checkFruits));
System.out.println("Is collection empty?: " +
collection.isEmpty());
System.out.println("Collection size: " +
collection.size());
Collection<String> retainFruits =
Arrays.asList("Elderberry", "Fig");
collection.retainAll(retainFruits);
System.out.println("Collection after retainAll(): " +
collection);
collection.clear();
System.out.println("Collection after clear(): " +
collection);
System.out.println("Is collection empty after clear()?: "
+ collection.isEmpty());
}
}
Arraylist
import java.util.*;
class ArrayListDemo {
public static void main(String args[])
{ // Create an array list.
ArrayList <String>al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
Generic
class Test<T> {
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}
// Driver class to test above
class Main {
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());
// instance of String type
Test<String> sObj
= new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
}
}
List example
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
class ListExample {
public static void main(String[] args) {
List<Integer> numbers = new
ArrayList<>(Arrays.asList(10, 20, 30, 40, 50));
numbers.add(2, 25);
System.out.println("After add(2, 25): " +
numbers);
List<Integer> extraNumbers = Arrays.asList(60, 70);
numbers.addAll(3, extraNumbers);
System.out.println("After addAll(3, [60, 70]): " +
numbers);
int valueAt4 = numbers.get(4);
System.out.println("Element at index 4: " +
valueAt4);
numbers.set(1, 15);
System.out.println("After set(1, 15): " + numbers);
int index = numbers.indexOf(30);
System.out.println("Index of 30: " + index);
numbers.add(30);
System.out.println("new list " + numbers);
int lastIndex = numbers.lastIndexOf(30);
System.out.println("Last index of 30: " + lastIndex);
List<Integer> subList = numbers.subList(2, 6);
System.out.println("SubList (2 to 5): " +
subList);
}
}
Linked List
import java.util.*;
class LinkedListDemo {
public static void main(String args[])
{
// Create a linked list.
LinkedList<String> ll = new LinkedList<String>();
// Add elements to the linked list.
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
ll.size();
System.out.println("Original contents of ll: " + ll);
ll.remove("F");
System.out.println("Contents of ll after deletion: " + ll);
ll.remove(2);
System.out.println("Contents of ll after deletion: " + ll);
// Remove first and last elements.
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "+ ll);
String val = ll.get(2);
System.out.println("val: " + val);
ll.set(2, val + " Changed");
System.out.println("ll after change: " + ll);
}
}
Navigable set
import java.util.*;
public class NavigableSetExample {
public static void main(String[] args) {
// NavigableSet<Integer> navSet = new
TreeSet<>(Arrays.asList(10, 20, 30, 40, 50));
NavigableSet<Integer> navSet = new TreeSet<>();
navSet.add(10);
navSet.add(30);
navSet.add(20);
navSet.add(20);
navSet.add(40);
navSet.add(50);
navSet.add(60);
System.out.println("elements are:"+navSet);
System.out.println("ceiling(25): " + navSet.ceiling(25));
System.out.println("floor(25): " + navSet.floor(25));
System.out.println("higher(30): " + navSet.higher(30));
System.out.println("lower(30): " + navSet.lower(30));
System.out.print("Descending order: ");
Iterator<Integer> descIt = navSet.descendingIterator();
while (descIt.hasNext()) {
System.out.print(descIt.next() + " ");
}
System.out.println();
System.out.println("Descending Set: " +
navSet.descendingSet());
System.out.println("headSet(40, true): " +
navSet.headSet(40));
System.out.println("tailSet(30, true): " +
navSet.tailSet(30));
System.out.println("subSet(20,40): " +
navSet.subSet(20,40));
System.out.println("pollFirst(): " +
navSet.pollFirst());
System.out.println("After pollFirst: " + navSet);
System.out.println("pollLast(): " + navSet.pollLast());
System.out.println("After pollLast: " + navSet);
}
}
SortedSet
import java.util.TreeSet;
import java.util.SortedSet;
public class SortedSetExample {
public static void main(String[] args) {
SortedSet<Integer> numbers = new TreeSet<>();
numbers.add(10);
numbers.add(30);
numbers.add(20);
numbers.add(50);
numbers.add(40);
System.out.println("SortedSet: " + numbers);
System.out.println("First Element: " + numbers.first());
System.out.println("Last Element: " + numbers.last());
SortedSet<Integer> subset = numbers.subSet(20, 40);
System.out.println("Subset (20 to 40): " + subset);
SortedSet<Integer> headset = numbers.headSet(30);
System.out.println("HeadSet (less than 30): " + headset);
SortedSet<Integer> tailset = numbers.tailSet(30);
System.out.println("TailSet (greater than or equal to
30): " + tailset);
}
}
Queue
import java.util.*;
public class QueueExample {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(10);
queue.offer(20);
queue.offer(30);
System.out.println("Queue after offer(): " + queue);
System.out.println("element(): " + queue.element());
System.out.println("peek(): " + queue.peek());
System.out.println("poll(): " + queue.poll());
System.out.println("Queue after poll(): " + queue);
System.out.println("remove(): " + queue.remove());
System.out.println("Queue after remove(): " + queue);
queue.poll();
try {
System.out.println("element(): " + queue.element());
}
catch (NoSuchElementException e) {
System.out.println("element() failed: Queue is
empty!");
}
try {
System.out.println("remove(): " + queue.remove());
}
catch (NoSuchElementException e) {
System.out.println("remove() failed: Queue is
empty!");
}
System.out.println("peek() on empty queue: " +
queue.peek()); // Output: null
System.out.println("poll() on empty queue: " +
queue.poll()); // Output: null*/
}
}
QueueDeque
import java.util.*;
public class QueueDequeExample {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(10);
queue.offer(20);
queue.offer(30);
System.out.println("Element(): " + queue.element()); //
Throws exception if empty
System.out.println("Peek(): " + queue.peek()); // Returns
null if empty
System.out.println("Poll(): " + queue.poll()); //
Returns null if empty
System.out.println("Remove(): " + queue.remove()); //
Throws exception if empty
Deque<Integer> deque = new LinkedList<>();
// Adding elements at first and last
deque.addFirst(100);
deque.addLast(200);
deque.offerFirst(50);
deque.offerLast(300);
// Accessing elements
System.out.println("GetFirst(): " + deque.getFirst()); //
Throws exception if empty
System.out.println("GetLast(): " + deque.getLast()); //
Throws exception if empty
System.out.println("PeekFirst(): " + deque.peekFirst());
// Returns null if empty
System.out.println("PeekLast(): " + deque.peekLast()); //
Returns null if empty
// Removing elements
System.out.println("PollFirst(): " + deque.pollFirst());
// Returns null if empty
System.out.println("PollLast(): " + deque.pollLast()); //
Returns null if empty
System.out.println("Pop(): " + deque.pop()); // Throws
exception if empty
deque.push(500); // Adds to front
// Removing first and last occurrence
deque.add(400);
deque.add(400);
System.out.println("RemoveFirstOccurrence(400): " +
deque.removeFirstOccurrence(400));
System.out.println("RemoveLastOccurrence(400): " +
deque.removeLastOccurrence(400));
// Iterating in reverse
System.out.println("Descending Iterator:");
Iterator<Integer> iterator = deque.descendingIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Foreach
import java.util.*;
class ForEachDemo {
public static void main(String args[]) {
// Create an array list for integers.
ArrayList<Integer> vals = new ArrayList<Integer>();
// Add values to the array list.
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
// Use for loop to display the values.
System.out.print("Contents of vals: ");
for(int v : vals)
System.out.print(v + " ");
System.out.println();
// Now, sum the values by using a for loop.
int sum = 0;
for(int v : vals)
sum += v;
System.out.println("Sum of values: " + sum);
}
}
Enumset
import java.util.EnumSet;
import java.util.List;
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY;
}
public class EnumSetDemo {
public static void main(String[] args) {
EnumSet<Day> allDays = EnumSet.allOf(Day.class);
System.out.println("All Days: " + allDays);
EnumSet<Day> weekdays = EnumSet.range(Day.MONDAY,
Day.FRIDAY);
EnumSet<Day> weekends = EnumSet.complementOf(weekdays);
System.out.println("Weekdays: " + weekdays);
System.out.println("Weekends: " + weekends);
EnumSet<Day> copyWeekdays = EnumSet.copyOf(weekdays);
System.out.println("Copy of Weekdays: " + copyWeekdays);
List<Day> someDaysList = List.of(Day.WEDNESDAY,
Day.FRIDAY);
EnumSet<Day> fromList = EnumSet.copyOf(someDaysList);
System.out.println("EnumSet from List: " + fromList);
EnumSet<Day> emptySet = EnumSet.noneOf(Day.class);
System.out.println("Empty EnumSet: " + emptySet);
EnumSet<Day> selectedDays = EnumSet.of(Day.MONDAY,
Day.WEDNESDAY, Day.FRIDAY);
System.out.println("Selected Days: " + selectedDays);
EnumSet<Day> singleDay = EnumSet.of(Day.TUESDAY);
System.out.println("Single Day: " + singleDay);
EnumSet<Day> twoDays = EnumSet.of(Day.THURSDAY,
Day.SATURDAY);
System.out.println("Two Days: " + twoDays);
EnumSet<Day> threeDays = EnumSet.of(Day.MONDAY,
Day.WEDNESDAY, Day.FRIDAY);
System.out.println("Three Days: " + threeDays);
EnumSet<Day> midWeek = EnumSet.range(Day.TUESDAY,
Day.THURSDAY);
System.out.println("Mid Week Days: " + midWeek);
}
}
Comparator
import java.util.*;
class students
{
String name;
int marks;
students(String s,int m)
{
name=s;
marks=m;
}
//public String toString()
// {
// return name+" "+marks;
//}
}
class studentnamecomp implements Comparator
{
public int compare(Object a,Object b)
{
students s1=(students)a;
students s2=(students)b;
return s1.name.compareTo(s2.name);
}
}
class studentsnamedescomp implements Comparator
{
public int compare(Object a,Object b)
{
students s1=(students)a;
students s2=(students)b;
return s2.name.compareTo(s1.name);
}
public class hash_obj_comp
{
public static void main(String args[])
{
students std1=new students("aa",89);
students std2=new students("ha",90);
students std3=new students("dk",76);
TreeSet<students> ts=new TreeSet<students>(new
studentnamecomp());
ts.add(std1);
ts.add(std2);
ts.add(std3);
System.out.println("ojects of the treeset based on name");
System.out.println(ts);
TreeSet<students> ts1=new TreeSet<students>(new
studentsnamedescomp());
ts1.add(std1);
ts1.add(std2);
ts1.add(std3);
System.out.println("ojects of the treeset based on name");
System.out.println(ts1);
}
}
Hashiterator
import java.util.HashSet;
import java.util.Iterator;
public class Hashiterator
{
public static void main(String[] args)
{
// Create a HashSet of Strings
HashSet<String> hs = new HashSet<>();
// Add elements to the HashSet
hs.add("A");
hs.add("B");
hs.add("Geeks");
hs.add("For");
hs.add("Geeks");
hs.add("Z");
// Using iterator() method to iterate
// Over the HashSet
System.out.print("Using iterator : ");
Iterator<String> iterator = hs.iterator();
// Traversing HashSet
while (iterator.hasNext())
System.out.print(iterator.next() + ", ");
System.out.println();
// Using enhanced for loop to iterate
// Over the HashSet
System.out.print("Using enhanced for loop : ");
for (String element : hs)
System.out.print(element + " , ");
}
}
Hashset
import java.util.*;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> defaultSet = new HashSet<>();
defaultSet.add("Apple");
defaultSet.add("Banana");
defaultSet.add("Cherry");
System.out.println("Default HashSet: " + defaultSet);
List<String> fruits = Arrays.asList("Mango", "Orange",
"Grapes");
HashSet<String> collectionSet = new HashSet<>(fruits);
System.out.println("HashSet from Collection: " +
collectionSet);
HashSet<Integer> capacitySet = new HashSet<>(10);
capacitySet.add(1);
capacitySet.add(2);
capacitySet.add(3);
System.out.println("HashSet with Capacity 10: " +
capacitySet);
HashSet<Double> customSet = new HashSet<>(5, 0.5f);
customSet.add(2.5);
customSet.add(3.5);
customSet.add(4.5);
System.out.println("HashSet with Custom Load Factor: " +
customSet);
}
}
Iterator
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
System.out.print("Original contents of al: ");
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
ListIterator<String> litr = al.listIterator();
while(litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Task(String name, int timestamp) {
this.name = name;
this.timestamp = timestamp;
}
@Override
public String toString() {
return name + " (" + timestamp + ")";
}
}
public class CustomPriorityQueue {
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<>(Comparator.comparingInt(task -> task.timestamp));
pq.add(new Task("Task1", 10));
pq.add(new Task("Task2", 5));
pq.add(new Task("Task3", 20));
while (!pq.isEmpty()) {
System.out.println(pq.poll());
}
}
}
nullsFirst(Comparator<? super T> comp)
import java.util.*;
public class NullsFirstExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("Banana", null, "Apple", "Mango", null);
// Sorting with nulls first
words.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
System.out.println("Sorted with nulls first: " + words);
}
}
nullsLast(Comparator<? super T> comp)
import java.util.*;
public class NullsLastExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("Banana", null, "Apple", "Mango", null);
// Sorting with nulls last
words.sort(Comparator.nullsLast(Comparator.naturalOrder()));
System.out.println("Sorted with nulls last: " + words);
}
}
thenComparing(Comparator<? super T> thenByComp)
import java.util.*;
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " (" + age + ")";
}
}
public class ThenComparingExample {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("John", 22),
new Student("Alice", 25),
new Student("Bob", 22),
new Student("Charlie", 20)
);
// Sort by age, then by name
students.sort(Comparator.comparingInt(s -> s.age)
.thenComparing(s -> s.name));
System.out.println("Sorted by age, then name: " + students);
}
}/// output: Sorted by age, then name: [Charlie (20), Bob (22), John (22), Alice (25)]
thenComparing(Function<? super T, ? extends U> getKey)
students.sort(Comparator.comparingInt(s -> s.age).thenComparing(Student::getName));
thenComparingDouble(ToDoubleFunction<? super T> getKey)
students.sort(Comparator.comparingDouble(Student::getGPA)
.thenComparing(Student::getName));
thenComparingInt(ToIntFunction<? super T> getKey)
students.sort(Comparator.comparingInt(Student::getAge)
.thenComparing(Student::getName));