Use enums, records and generics, store data in Lists, Sets and Maps, and process it with lambdas and streams.
Every code example has a ▶ Run button. Click ✎ Edit, or press L, to open the Code Lab.
java Main.javajava Main.java in the folder D:\java-practice.OrderStatus.OUT_FOR_DELIVERY with an enum, not a stringList<Student>, Map<String, Integer>| Primitive | Wrapper |
|---|---|
| int | Integer |
| double | Double |
| char | Character |
| boolean | Boolean |
| long | Long |
1enum Signal { RED, YELLOW, GREEN }23public class Main {4 static String action(Signal s) {5 return switch (s) {6 case RED -> "Stop";7 case YELLOW -> "Get ready";8 case GREEN -> "Go";9 };10 }1112 public static void main(String[] args) {13 Signal now = Signal.RED;14 System.out.println(now + ": " + action(now));15 for (Signal s : Signal.values()) {16 System.out.println(s.ordinal() + " " + s + " -> " + action(s));17 }18 Signal fromText = Signal.valueOf("GREEN");19 System.out.println("Parsed: " + fromText);20 }21}
"Gren" that a String would allow. values() lists them; valueOf() converts text.1enum OrderStatus {2 PLACED("Order placed", 10),3 PACKED("Packed at store", 30),4 SHIPPED("On the way", 70),5 DELIVERED("Delivered", 100);67 private final String label;8 private final int progress;910 OrderStatus(String label, int progress) { // enum constructor11 this.label = label;12 this.progress = progress;13 }14 String bar() { return "#".repeat(progress / 10) + ".".repeat(10 - progress / 10); }15 OrderStatus next() {16 return this == DELIVERED ? DELIVERED : values()[ordinal() + 1];17 }18 String getLabel() { return label; }19}2021public class Main {22 public static void main(String[] args) {23 OrderStatus s = OrderStatus.PLACED;24 for (int i = 0; i < 4; i++) {25 System.out.printf("%-9s [%s] %s%n", s, s.bar(), s.getLabel());26 s = s.next();27 }28 }29}
1record Student(String name, int roll, double marks) {2 Student { // validation3 if (marks < 0 || marks > 100) throw new IllegalArgumentException("bad marks");4 }5 String grade() { return marks >= 90 ? "A+" : marks >= 75 ? "A" : "B"; }6}78public class Main {9 public static void main(String[] args) {10 Student s = new Student("Priya", 14, 91.5);11 System.out.println(s); // toString for free12 System.out.println(s.name() + " got " + s.grade()); // accessor: name()13 Student t = new Student("Priya", 14, 91.5);14 System.out.println("equal? " + s.equals(t)); // equals for free15 }16}
record (Java 16+) creates an immutable data class with a constructor, getters (name()), equals, hashCode and toString automatically. Perfect for data carried between parts of an app.| Class with 3 fields | record |
|---|---|
| ~40 lines | 1 line |
| setters possible | immutable |
| getName() | name() |
1class Box<T> { // T = a type chosen later2 private T item;3 void put(T item) { this.item = item; }4 T get() { return item; }5}67public class Main {8 public static void main(String[] args) {9 Box<String> gift = new Box<>();10 gift.put("Smart watch");11 String g = gift.get(); // no cast needed1213 Box<Integer> marks = new Box<>();14 marks.put(95);15 int m = marks.get() + 5; // unboxing1617 System.out.println(g + ", " + m);18 // gift.put(42); // compile ERROR: not a String19 }20}
Box<String> accepts only Strings. <> (diamond) lets Java infer the type.ArrayList<String> and HashMap<String, Integer> work (Modules 15-16).1import java.util.Arrays;23record Pair<A, B>(A first, B second) { }45public class Main {6 static <T> void printAll(T[] items) { // any type7 for (T x : items) System.out.print(x + " | ");8 System.out.println();9 }10 static <T extends Comparable<T>> T max(T[] items) { // only comparable types11 T best = items[0];12 for (T x : items) if (x.compareTo(best) > 0) best = x;13 return best;14 }1516 public static void main(String[] args) {17 Integer[] runs = {45, 102, 67};18 String[] cities = {"Ranchi", "Bokaro", "Deoghar"};19 printAll(runs);20 printAll(cities);21 System.out.println("max run: " + max(runs) + ", last city: " + max(cities));22 Pair<String, Integer> p = new Pair<>("Hundru Falls", 98);23 System.out.println(p.first() + " is " + p.second() + " m high");24 }25}
<T> before the return type makes a generic method. <T extends Comparable<T>> is a bound: only types that can be compared are allowed. Records can be generic too.java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).EXTRA_LARGE sizeCrust enum (THIN, CHEESE_BURST +Rs 99)<T> T last(T[] a)1public class Wrappers {2 public static void main(String[] args) {3 int qty = Integer.parseInt("12");4 double price = Double.parseDouble("45.50");5 boolean paid = Boolean.parseBoolean("true");6 System.out.println("Total: " + qty * price + ", paid " + paid);7 String s = String.valueOf(qty * price);8 System.out.println("As text: \"" + s + "\" length " + s.length());9 System.out.println("int range: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);10 System.out.println("Binary of 12: " + Integer.toBinaryString(12));11 }12}
1enum Day {2 MON, TUE, WED, THU, FRI, SAT, SUN;3 boolean isHoliday() { return this == SUN; }4}56public class Timetable {7 public static void main(String[] args) {8 for (Day d : Day.values()) {9 System.out.println(d + (d.isHoliday() ? " - holiday" : " - school"));10 }11 }12}
1record Result(String name, int roll, double percent) { }23public class Results {4 public static void main(String[] args) {5 Result a = new Result("Ankita", 3, 88.4);6 Result b = new Result("Bhola", 7, 72.0);7 Result c = new Result("Ankita", 3, 88.4);8 System.out.println(a);9 System.out.println(b.name() + " scored " + b.percent());10 System.out.println("a equals c? " + a.equals(c));11 }12}
1enum Slab {2 LOW(0, 100, 4.0), MID(101, 200, 5.5), HIGH(201, 400, 6.8), PEAK(401, Integer.MAX_VALUE, 8.0);3 final int min, max; final double rate;4 Slab(int min, int max, double rate) { this.min = min; this.max = max; this.rate = rate; }5 static Slab of(int units) {6 for (Slab s : values()) if (units >= s.min && units <= s.max) return s;7 throw new IllegalArgumentException("bad units");8 }9}1011public class SlabBill {12 public static void main(String[] args) {13 int[] usage = {85, 160, 340, 520};14 for (int u : usage) {15 Slab s = Slab.of(u);16 System.out.printf("%3d units -> %-4s @ Rs %.1f = Rs %.2f%n", u, s, s.rate, u * s.rate);17 }18 }19}
Pair<A, B> lets one method return two values of any type.1record Pair<A, B>(A first, B second) { }23public class PairDemo {4 static Pair<Integer, Integer> minMax(int[] a) {5 int lo = a[0], hi = a[0];6 for (int x : a) { lo = Math.min(lo, x); hi = Math.max(hi, x); }7 return new Pair<>(lo, hi);8 }9 static Pair<String, Integer> topper(String[] names, int[] marks) {10 int best = 0;11 for (int i = 1; i < marks.length; i++) if (marks[i] > marks[best]) best = i;12 return new Pair<>(names[best], marks[best]);13 }14 public static void main(String[] args) {15 int[] m = {67, 92, 45, 88};16 String[] n = {"Aman", "Bina", "Chirag", "Diya"};17 Pair<Integer, Integer> mm = minMax(m);18 System.out.println("Lowest " + mm.first() + ", highest " + mm.second());19 Pair<String, Integer> t = topper(n, m);20 System.out.println("Topper: " + t.first() + " (" + t.second() + ")");21 }22}
1enum Status {2 PLACED, ACCEPTED, COOKING, OUT_FOR_DELIVERY, DELIVERED, CANCELLED;3 boolean canMoveTo(Status n) {4 if (n == CANCELLED) return this == PLACED || this == ACCEPTED;5 return this != CANCELLED && this != DELIVERED && n.ordinal() == ordinal() + 1;6 }7}89public class Tracking {10 public static void main(String[] args) {11 Status s = Status.PLACED;12 Status[] events = {Status.ACCEPTED, Status.DELIVERED, Status.COOKING, Status.CANCELLED, Status.OUT_FOR_DELIVERY, Status.DELIVERED};13 System.out.println("Order #A77: " + s);14 for (Status e : events) {15 if (s.canMoveTo(e)) {16 s = e;17 System.out.println(" -> " + s);18 } else {19 System.out.println(" x cannot go from " + s + " to " + e);20 }21 }22 }23}
1class Stack<T> {2 private Object[] data = new Object[10];3 private int size;4 void push(T x) { data[size++] = x; }5 @SuppressWarnings("unchecked")6 T pop() { return (T) data[--size]; }7 @SuppressWarnings("unchecked")8 T peek() { return (T) data[size - 1]; }9 boolean isEmpty() { return size == 0; }10}1112public class Undo {13 public static void main(String[] args) {14 Stack<String> history = new Stack<>();15 Stack<Integer> cursor = new Stack<>();16 String[] edits = {"Hello", "Hello Ranchi", "Hello Ranchi!!"};17 for (String e : edits) { history.push(e); cursor.push(e.length()); }18 System.out.println("Now: " + history.peek() + " (cursor " + cursor.peek() + ")");19 history.pop(); cursor.pop();20 System.out.println("Undo: " + history.peek() + " (cursor " + cursor.peek() + ")");21 history.pop(); cursor.pop();22 System.out.println("Undo: " + history.peek() + " (cursor " + cursor.peek() + ")");23 }24}
<T extends Number> lets you call doubleValue() on any numeric wrapper.1public class Stats {2 static <T extends Number> double average(T[] a) {3 double s = 0;4 for (T x : a) s += x.doubleValue();5 return s / a.length;6 }7 static <T extends Number> T max(T[] a) {8 T best = a[0];9 for (T x : a) if (x.doubleValue() > best.doubleValue()) best = x;10 return best;11 }12 public static void main(String[] args) {13 Integer[] marks = {78, 91, 66, 85};14 Double[] prices = {45.5, 120.0, 99.99};15 System.out.printf("Marks avg %.2f, max %d%n", average(marks), max(marks));16 System.out.printf("Prices avg %.2f, max %.2f%n", average(prices), max(prices));17 // average(new String[]{"a"}); // ERROR: String is not a Number18 }19}
1enum Category {2 TABLET(12), SYRUP(12), DEVICE(18), AYURVEDIC(5);3 final int gst;4 Category(int g) { gst = g; }5}6record Medicine(String name, Category cat, double price, int stock) {7 double priceWithGst() { return price * (100 + cat.gst) / 100; }8}9record Result<T>(T value, String error) {10 static <T> Result<T> ok(T v) { return new Result<>(v, null); }11 static <T> Result<T> fail(String e) { return new Result<>(null, e); }12 boolean isOk() { return error == null; }13}1415public class Pharmacy {16 static Result<Medicine> parse(String line) {17 String[] f = line.split(";");18 if (f.length != 4) return Result.fail("expected 4 fields: " + line);19 try {20 return Result.ok(new Medicine(f[0], Category.valueOf(f[1]), Double.parseDouble(f[2]), Integer.parseInt(f[3])));21 } catch (IllegalArgumentException e) { // also catches NumberFormatException22 return Result.fail("bad value in: " + line);23 }24 }25 public static void main(String[] args) {26 String[] lines = {"Paracetamol 500;TABLET;30;200", "Cough syrup;SYRUP;95.5;40", "BP monitor;DEVICE;1499;x", "Chyawanprash;AYURVEDIC;320;25", "Thermometer;GADGET;250;10"};27 for (String l : lines) {28 Result<Medicine> r = parse(l);29 if (r.isOk()) {30 Medicine m = r.value();31 System.out.printf("%-16s %-9s Rs %8.2f (incl %d%% GST) stock %d%n", m.name(), m.cat(), m.priceWithGst(), m.cat().gst, m.stock());32 } else {33 System.out.println("ERROR " + r.error());34 }35 }36 }37}
T extends Comparable<T>, records implementing Comparable, and insertion into a sorted array.1import java.util.Arrays;23class Leaderboard<T extends Comparable<T>> {4 private final Object[] top;5 private int size;6 Leaderboard(int n) { top = new Object[n]; }7 @SuppressWarnings("unchecked")8 void add(T x) {9 if (size < top.length) top[size++] = x;10 else if (x.compareTo((T) top[size - 1]) > 0) top[size - 1] = x;11 else return;12 int i = size - 1;13 while (i > 0 && ((T) top[i]).compareTo((T) top[i - 1]) > 0) {14 Object t = top[i]; top[i] = top[i - 1]; top[i - 1] = t; i--;15 }16 }17 String show() { return Arrays.toString(Arrays.copyOf(top, size)); }18}19record Player(String name, int score) implements Comparable<Player> {20 public int compareTo(Player o) { return Integer.compare(score, o.score); }21}22record Team(String name, double points) implements Comparable<Team> {23 public int compareTo(Team o) { return Double.compare(points, o.points); }24}2526public class Board {27 public static void main(String[] args) {28 Leaderboard<Player> lb = new Leaderboard<>(3);29 int[] sc = {40, 75, 62, 90, 55};30 String[] nm = {"Asha", "Bunty", "Chinu", "Dev", "Ekta"};31 for (int i = 0; i < sc.length; i++) { lb.add(new Player(nm[i], sc[i])); System.out.println(lb.show()); }32 Leaderboard<Team> tb = new Leaderboard<>(2);33 tb.add(new Team("Ranchi Rhinos", 12.5)); tb.add(new Team("Dhanbad Dynamos", 15)); tb.add(new Team("Bokaro Bulls", 9));34 System.out.println(tb.show());35 }36}
parseInt; compare with equalsenum: fixed named constants; values(), valueOf(), switchrecord: immutable data class with free accessors, equals, toStringBox<T>: one class, any type, compile-time safety<T>, bounds <T extends Number>Integer.parseInt("42") returns...
Accessor for field name in a record is...
Box<String> b; b.put(5);
Listjava.util) gives ready-made data structures. Interfaces (List, Set, Queue) say what you can do; classes (ArrayList, HashSet...) are the implementations.| Need | Use |
|---|---|
| ordered list, index access | ArrayList |
| no duplicates, fast check | HashSet |
| sorted unique values | TreeSet |
| first come first served | ArrayDeque |
| most urgent first | PriorityQueue |
List<String> names = new ArrayList<>();1import java.util.ArrayList;2import java.util.List;34public class Main {5 public static void main(String[] args) {6 List<String> cart = new ArrayList<>();7 cart.add("Rice 5kg");8 cart.add("Dal 1kg");9 cart.add("Oil 1L");10 cart.add(1, "Sugar 1kg"); // insert at index 111 System.out.println(cart + " size " + cart.size());1213 System.out.println("First: " + cart.get(0));14 cart.set(2, "Moong dal 1kg"); // replace15 cart.remove("Oil 1L"); // by value16 System.out.println("Has sugar? " + cart.contains("Sugar 1kg"));17 System.out.println("Index of sugar: " + cart.indexOf("Sugar 1kg"));18 System.out.println(cart);19 cart.clear();20 System.out.println("Empty? " + cart.isEmpty());21 }22}
ArrayList is like an array that resizes itself. It keeps insertion order, allows duplicates and gives index access. Store objects only: List<Integer>, not List<int>.| Method | Does |
|---|---|
add(x) / add(i, x) | append / insert |
get(i), set(i, x) | read / replace |
remove(i or x) | delete |
size(), contains(x) | count / search |
remove(1) on a List<Integer> removes index 1; use remove(Integer.valueOf(1)) to remove the value 1.1import java.util.*;23public class Main {4 public static void main(String[] args) {5 List<Integer> marks = new ArrayList<>(List.of(78, 28, 91, 30, 66, 12));67 for (int m : marks) System.out.print(m + " "); // for-each8 System.out.println();9 for (int i = 0; i < marks.size(); i++) { // index10 if (i % 2 == 0) System.out.print("[" + i + "]=" + marks.get(i) + " ");11 }12 System.out.println();1314 Iterator<Integer> it = marks.iterator(); // remove while looping15 while (it.hasNext()) {16 if (it.next() < 33) it.remove();17 }18 System.out.println("Passed: " + marks);1920 List<Integer> extra = new ArrayList<>(List.of(5, 40, 8));21 extra.removeIf(x -> x < 10); // modern way22 System.out.println("removeIf: " + extra);23 }24}
Iterator or removeIf; removing inside a for-each throws ConcurrentModificationException.List.of(...) makes an unmodifiable list; wrap it in new ArrayList<>(...) to change it.1import java.util.*;23record Item(String name, double price, int qty) {4 double total() { return price * qty; }5}67public class Main {8 public static void main(String[] args) {9 List<Item> cart = new ArrayList<>();10 cart.add(new Item("Earphones", 799, 1));11 cart.add(new Item("Notebook", 45, 6));12 cart.add(new Item("Pen pack", 120, 2));1314 double sum = 0;15 for (Item i : cart) sum += i.total();16 System.out.println(cart.size() + " items, bill Rs " + sum);1718 List<String> names = new ArrayList<>();19 for (Item i : cart) names.add(i.name());20 Collections.sort(names);21 System.out.println("Sorted: " + names);22 Collections.reverse(names);23 System.out.println("Reversed: " + names + ", max: " + Collections.max(names));24 }25}
List<Item> holds objects; loop to compute totals. The Collections class (with an s) has static helpers: sort, reverse, shuffle, max, min, frequency.1import java.util.*;23public class Main {4 public static void main(String[] args) {5 String[] visits = {"aman", "riya", "aman", "zoya", "riya", "kunal", "aman"};67 Set<String> hash = new HashSet<>();8 Set<String> linked = new LinkedHashSet<>();9 Set<String> tree = new TreeSet<>();10 for (String v : visits) {11 hash.add(v);12 linked.add(v);13 tree.add(v);14 }15 System.out.println("Visits: " + visits.length + ", unique: " + hash.size());16 System.out.println("LinkedHashSet (first-seen order): " + linked);17 System.out.println("TreeSet (sorted): " + tree);18 System.out.println("add aman again? " + hash.add("aman"));19 System.out.println("contains zoya? " + hash.contains("zoya"));20 }21}
add returns false for a duplicate. HashSet is fastest (no order), LinkedHashSet keeps insertion order, TreeSet keeps values sorted.equals and hashCode to spot duplicates: override them in your own classes (Module 11).addAll = union, retainAll = intersection, removeAll = difference. Copy first, because these methods change the set.1import java.util.*;23public class Main {4 public static void main(String[] args) {5 Queue<String> counter = new ArrayDeque<>(); // token queue6 counter.offer("T101 Ramesh");7 counter.offer("T102 Sunita");8 counter.offer("T103 Arif");9 System.out.println("Next: " + counter.peek());10 while (!counter.isEmpty()) {11 System.out.println("Serving " + counter.poll());12 }1314 Deque<String> back = new ArrayDeque<>(); // stack: last in, first out15 back.push("home");16 back.push("products");17 back.push("cart");18 System.out.println("Back -> " + back.pop() + ", then " + back.peek());19 }20}
offer adds at the back, poll removes from the front, peek looks. ArrayDeque also works as a stack with push/pop (last in, first out).| Queue | Stack |
|---|---|
| offer / poll / peek | push / pop / peek |
| ticket counter | browser back button |
| FIFO | LIFO |
poll() returns null on an empty queue, while remove() throws an exception.1import java.util.*;23record Patient(String name, int severity) { } // 1 = most urgent45public class Main {6 public static void main(String[] args) {7 PriorityQueue<Patient> er = new PriorityQueue<>(Comparator.comparingInt(Patient::severity));8 er.add(new Patient("Mohan (fever)", 4));9 er.add(new Patient("Seema (accident)", 1));10 er.add(new Patient("Rafiq (fracture)", 2));11 er.add(new Patient("Lata (cough)", 5));12 while (!er.isEmpty()) {13 Patient p = er.poll();14 System.out.println("Treating " + p.name() + " [level " + p.severity() + "]");15 }16 PriorityQueue<Integer> nums = new PriorityQueue<>(List.of(40, 10, 30, 20));17 System.out.println("smallest first: " + nums.poll() + ", " + nums.poll());18 }19}
PriorityQueue always gives the highest-priority element on poll(). By default that is the smallest; pass a Comparator to decide priority (more in Module 16).java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).Task(String name, int priority)1import java.util.*;23public class Attendance {4 public static void main(String[] args) {5 List<String> present = new ArrayList<>();6 present.add("Aditi"); present.add("Bablu"); present.add("Chanda"); present.add("Deepak"); present.add("Esha");7 present.remove("Bablu");8 System.out.println("Present (" + present.size() + "): " + present);9 System.out.println("Is Deepak present? " + present.contains("Deepak"));10 System.out.println("Is Bablu present? " + present.contains("Bablu"));11 }12}
1import java.util.*;23public class MarksStats {4 public static void main(String[] args) {5 List<Integer> marks = new ArrayList<>(List.of(67, 88, 45, 92, 73, 59));6 int sum = 0;7 for (int m : marks) sum += m;8 System.out.println("Marks: " + marks);9 System.out.printf("Total %d, average %.2f%n", sum, sum / (double) marks.size());10 System.out.println("Highest " + Collections.max(marks) + ", lowest " + Collections.min(marks));11 Collections.sort(marks);12 System.out.println("Sorted: " + marks);13 }14}
1import java.util.*;23public class UniqueEmails {4 public static void main(String[] args) {5 String[] signups = {"riya@gmail.com", "Aman@yahoo.in", "RIYA@gmail.com", "zoya@outlook.com", "aman@yahoo.in"};6 Set<String> unique = new LinkedHashSet<>();7 for (String e : signups) unique.add(e.toLowerCase());8 System.out.println(signups.length + " sign-ups, " + unique.size() + " unique:");9 for (String e : unique) System.out.println(" " + e);10 }11}
1import java.util.*;23record Product(String name, int price, boolean inStock) { }45public class Wishlist {6 public static void main(String[] args) {7 List<Product> wish = new ArrayList<>(List.of(new Product("Shoes", 1799, true), new Product("Watch", 2499, false), new Product("Bag", 999, true)));8 List<Product> cart = new ArrayList<>();9 for (String want : new String[]{"Shoes", "Watch"}) {10 for (Product p : wish) if (p.name().equals(want)) { cart.add(p); break; }11 }12 wish.removeAll(cart);13 cart.removeIf(p -> !p.inStock());14 int total = 0;15 for (Product p : cart) total += p.price();16 System.out.println("Wishlist: " + wish);17 System.out.println("Cart: " + cart + " total Rs " + total);18 }19}
1import java.util.*;23public class Browser {4 static Deque<String> back = new ArrayDeque<>(), fwd = new ArrayDeque<>();5 static String current = "home";6 static void visit(String u) { back.push(current); current = u; fwd.clear(); System.out.println("visit " + current); }7 static void goBack() { if (!back.isEmpty()) { fwd.push(current); current = back.pop(); } System.out.println("back " + current); }8 static void goForward() { if (!fwd.isEmpty()) { back.push(current); current = fwd.pop(); } System.out.println("forward " + current); }910 public static void main(String[] args) {11 visit("jharkhand.gov.in"); visit("results"); visit("class-10");12 goBack(); goBack(); goForward();13 visit("admit-card");14 goForward();15 System.out.println("Back stack: " + back);16 }17}
1import java.util.*;23record Emergency(String name, int severity) { }45public class Opd {6 static Queue<String> normal = new ArrayDeque<>();7 static PriorityQueue<Emergency> urgent = new PriorityQueue<>(Comparator.comparingInt(Emergency::severity));8 static int token = 100;910 static void arrive(String n) { normal.offer("T" + (++token) + " " + n); }11 static void serveNext() {12 if (!urgent.isEmpty()) System.out.println("EMERGENCY -> " + urgent.poll().name());13 else if (!normal.isEmpty()) System.out.println("Counter -> " + normal.poll());14 else System.out.println("No patients");15 }1617 public static void main(String[] args) {18 arrive("Mohan"); arrive("Geeta"); arrive("Imran");19 serveNext();20 urgent.add(new Emergency("Accident case", 1));21 urgent.add(new Emergency("High fever child", 3));22 serveNext(); serveNext(); serveNext(); serveNext(); serveNext();23 }24}
1import java.util.*;23public class Friends {4 public static void main(String[] args) {5 Set<String> aman = new TreeSet<>(List.of("Riya", "Dev", "Kunal", "Sana"));6 Set<String> riya = new TreeSet<>(List.of("Aman", "Dev", "Sana", "Tara", "Vikas"));7 Set<String> mutual = new TreeSet<>(aman);8 mutual.retainAll(riya);9 Set<String> suggest = new TreeSet<>(riya);10 suggest.removeAll(aman);11 suggest.remove("Aman");12 System.out.println("Mutual friends: " + mutual + " (" + mutual.size() + ")");13 System.out.println("People Aman may know: " + suggest);14 }15}
1import java.util.*;23record Request(String member, boolean cancelled) { }45public class Waitlist {6 public static void main(String[] args) {7 List<Request> list = new ArrayList<>(List.of(new Request("Asha", false), new Request("Binod", true), new Request("Chetna", false), new Request("Dilip", true), new Request("Ekta", false)));8 Iterator<Request> it = list.iterator();9 while (it.hasNext()) {10 Request r = it.next();11 if (r.cancelled()) {12 System.out.println("Removed " + r.member());13 it.remove();14 }15 }16 Queue<Request> q = new ArrayDeque<>(list);17 int copies = 2;18 while (copies-- > 0 && !q.isEmpty()) System.out.println("Allotted to " + q.poll().member());19 System.out.println("Still waiting: " + q.size());20 }21}
1import java.util.*;23public class Seating {4 public static void main(String[] args) {5 int[] raw = {1203, 1187, 1250, 1203, 1199, 1222, 1187, 1240, 1211, 1233};6 Set<Integer> rolls = new TreeSet<>();7 for (int r : raw) rolls.add(r);8 System.out.println("Unique rolls (" + rolls.size() + "): " + rolls);9 List<Integer> order = new ArrayList<>(rolls);10 Collections.shuffle(order, new Random(7));11 int room = 101;12 for (int i = 0; i < order.size(); i += 4) {13 List<Integer> chunk = order.subList(i, Math.min(i + 4, order.size()));14 System.out.println("Room " + room++ + ": " + chunk);15 }16 }17}
1import java.util.*;23record Job(String file, int pages, boolean urgent) { }45public class PrintQueue {6 public static void main(String[] args) {7 Comparator<Job> order = Comparator.comparing((Job j) -> !j.urgent()).thenComparingInt(Job::pages);8 PriorityQueue<Job> pq = new PriorityQueue<>(order);9 Set<String> queued = new HashSet<>();10 Job[] incoming = {new Job("salary.pdf", 12, false), new Job("notice.docx", 1, true), new Job("report.pdf", 40, false),11 new Job("salary.pdf", 12, false), new Job("admit-card.pdf", 2, true), new Job("menu.png", 1, false)};12 for (Job j : incoming) {13 if (queued.add(j.file())) pq.add(j);14 else System.out.println("Skipped duplicate " + j.file());15 }16 int pages = 0;17 while (!pq.isEmpty()) {18 Job j = pq.poll();19 pages += j.pages();20 System.out.printf("%-15s %3d pages %s%n", j.file(), j.pages(), j.urgent() ? "URGENT" : "");21 }22 System.out.println("Total pages printed: " + pages);23 }24}
List<Integer>)ArrayList: ordered, duplicates, index access: add, get, set, remove, sizeIterator or removeIfHashSet (fast), LinkedHashSet (order), TreeSet (sorted): no duplicatesPriorityQueue: most important first, with a ComparatorWhich allows duplicates and keeps order?
set.add("x") when "x" is already there returns...
Which serves first-come first-served?
Map<String, Object>| Class | Order of keys |
|---|---|
HashMap | no fixed order (fastest) |
LinkedHashMap | insertion order |
TreeMap | sorted by key |
Map<String, Integer>: first type = key, second = value.1import java.util.*;23public class Main {4 public static void main(String[] args) {5 Map<String, String> phone = new HashMap<>();6 phone.put("Riya", "98350 11223");7 phone.put("Aman", "70040 55667");8 phone.put("Sana", "62000 88990");9 phone.put("Aman", "70040 00000"); // same key: value replaced1011 System.out.println("Aman: " + phone.get("Aman"));12 System.out.println("Ravi: " + phone.get("Ravi")); // missing -> null13 System.out.println("Ravi: " + phone.getOrDefault("Ravi", "not saved"));14 System.out.println("Has Sana? " + phone.containsKey("Sana"));15 phone.remove("Riya");16 System.out.println(phone.size() + " contacts, names " + new TreeSet<>(phone.keySet()));17 }18}
put(k, v) adds or replaces, get(k) returns the value or null, getOrDefault avoids null, containsKey checks, keySet() and values() give the parts.merge(key, 1, Integer::sum) is the standard way to count: it inserts 1 for a new key or adds 1 to the existing value.| Method | Does |
|---|---|
putIfAbsent(k, v) | only if missing |
merge(k, v, f) | combine values |
computeIfAbsent | create value on demand |
1import java.util.*;23public class Main {4 public static void main(String[] args) {5 Map<String, Integer> sales = new TreeMap<>(); // sorted by key6 sales.put("Mar", 41000);7 sales.put("Jan", 52000);8 sales.put("Feb", 38500);910 int total = 0;11 for (Map.Entry<String, Integer> e : sales.entrySet()) {12 System.out.printf("%s Rs %,7d %s%n", e.getKey(), e.getValue(), "#".repeat(e.getValue() / 5000));13 total += e.getValue();14 }15 System.out.printf("Total Rs %,d%n", total);1617 sales.forEach((month, amt) -> {18 if (amt > 40000) System.out.println(month + " crossed target");19 });20 }21}
entrySet() gives every key-value pair as a Map.Entry with getKey() and getValue(). forEach((k, v) -> ...) is the short lambda version.The counting pattern: one line inside the loop builds a frequency table. Watch count grow.
1import java.util.*;23public class Main {4 public static void main(String[] args) {5 String[] votes = {"Lotus", "Hand", "Lotus", "Bow", "Lotus", "Hand"};6 Map<String, Integer> count = new TreeMap<>();7 for (String v : votes) {8 count.merge(v, 1, Integer::sum);9 }10 System.out.println(count);11 }12}
1import java.util.*;23class Student implements Comparable<Student> {4 String name; int marks;5 Student(String n, int m) { name = n; marks = m; }67 @Override8 public int compareTo(Student other) {9 return Integer.compare(other.marks, this.marks); // higher marks first10 }11 public String toString() { return name + "(" + marks + ")"; }12}1314public class Main {15 public static void main(String[] args) {16 List<Student> list = new ArrayList<>(List.of(new Student("Aman", 78), new Student("Bina", 95), new Student("Chirag", 61), new Student("Diya", 88)));17 Collections.sort(list); // uses compareTo18 System.out.println("Merit list: " + list);19 TreeSet<Student> top = new TreeSet<>(list);20 System.out.println("Topper: " + top.first());21 }22}
compareTo returns negative (this comes first), 0 (equal) or positive (other comes first). Collections.sort, TreeSet and TreeMap use it automatically.Integer.compare(a, b) rather than a - b, which can overflow.1import java.util.*;23record Phone(String model, int price, double rating, int ramGb) { }45public class Main {6 public static void main(String[] args) {7 List<Phone> phones = new ArrayList<>(List.of(8 new Phone("Redmi 13", 11999, 4.2, 6), new Phone("Galaxy M35", 17999, 4.3, 8),9 new Phone("Moto G64", 14999, 4.3, 8), new Phone("Nord CE4", 24999, 4.5, 8)));1011 phones.sort(Comparator.comparingInt(Phone::price));12 System.out.println("Price low-high: " + names(phones));1314 phones.sort(Comparator.comparingDouble(Phone::rating).reversed()15 .thenComparingInt(Phone::price));16 System.out.println("Best rated, then cheaper: " + names(phones));1718 phones.sort((a, b) -> a.model().compareTo(b.model()));19 System.out.println("A-Z: " + names(phones));20 }21 static List<String> names(List<Phone> l) {22 List<String> n = new ArrayList<>();23 for (Phone p : l) n.add(p.model());24 return n;25 }26}
Comparator.comparing(...), flip with .reversed(), and break ties with .thenComparing(...).| Question | Answer |
|---|---|
| Need key -> value lookup? | HashMap (sorted keys: TreeMap) |
| Ordered items, duplicates OK? | ArrayList |
| Unique items? | HashSet / TreeSet |
| First come first served? | ArrayDeque |
| Most urgent first? | PriorityQueue |
| Undo / back history? | ArrayDeque as stack |
| Group items by category? | Map<K, List<V>> |
1Map<String, List<String>> byCity = new TreeMap<>();2byCity.computeIfAbsent("Ranchi", k -> new ArrayList<>())3 .add("Aditi");
java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).Map<Integer, List<String>>1import java.util.*;23public class PhoneBook {4 public static void main(String[] args) {5 Map<String, String> book = new HashMap<>();6 book.put("Mahto Electricals", "98350 12345");7 book.put("Gupta Sweets", "70040 22334");8 book.put("Lakra Tailors", "62039 44556");9 book.put("Singh Medicals", "91234 99887");10 System.out.println(book.getOrDefault("Gupta Sweets", "not found"));11 System.out.println(book.getOrDefault("Roy Hardware", "not found"));12 book.put("Gupta Sweets", "70040 00001");13 for (Map.Entry<String, String> e : new TreeMap<>(book).entrySet()) System.out.println(e.getKey() + " : " + e.getValue());14 }15}
1import java.util.*;23public class WordCount {4 public static void main(String[] args) {5 String s = "the river subarnarekha flows through ranchi and the river is beautiful";6 Map<String, Integer> c = new TreeMap<>();7 for (String w : s.split(" ")) c.merge(w, 1, Integer::sum);8 System.out.println(c);9 System.out.println("Distinct words: " + c.size());10 }11}
1import java.util.*;23public class Catalogue {4 public static void main(String[] args) {5 Map<String, Double> price = Map.of("P01", 45.0, "P02", 120.0, "P03", 15.5, "P04", 299.0, "P05", 60.0);6 String[] scanned = {"P02", "P03", "P03", "P09", "P05"};7 double bill = 0;8 for (String code : scanned) {9 Double p = price.get(code);10 if (p == null) System.out.println("Unknown code " + code);11 else bill += p;12 }13 System.out.println("Bill: Rs " + bill);14 }15}
1import java.util.*;23public class Election {4 public static void main(String[] args) {5 String[] votes = {"Meena", "Ravi", "Meena", "Arjun", "Ravi", "Meena", "Arjun", "Meena", "Ravi"};6 Map<String, Integer> c = new LinkedHashMap<>();7 for (String v : votes) c.merge(v, 1, Integer::sum);8 String win = null; int best = -1, second = -1;9 for (Map.Entry<String, Integer> e : c.entrySet()) {10 System.out.printf("%-6s %s %d%n", e.getKey(), "#".repeat(e.getValue()), e.getValue());11 if (e.getValue() > best) { second = best; best = e.getValue(); win = e.getKey(); }12 else if (e.getValue() > second) second = e.getValue();13 }14 System.out.println("Winner: " + win + " by " + (best - second) + " votes");15 }16}
1import java.util.*;23record Product(String name, int price, double rating) { }45public class SortBy {6 public static void main(String[] args) {7 List<Product> l = new ArrayList<>(List.of(new Product("Kurta", 899, 4.1), new Product("Saree", 2499, 4.6), new Product("Jacket", 1999, 4.1), new Product("Shawl", 699, 4.4)));8 l.sort(Comparator.comparingInt(Product::price));9 System.out.println("Price : " + l);10 l.sort(Comparator.comparingDouble(Product::rating).reversed().thenComparingInt(Product::price));11 System.out.println("Rating : " + l);12 l.sort(Comparator.comparing(Product::name));13 System.out.println("Name : " + l);14 }15}
1import java.util.*;23record Student(String name, String city) { }45public class Routes {6 public static void main(String[] args) {7 List<Student> all = List.of(new Student("Aman", "Ranchi"), new Student("Pooja", "Ramgarh"), new Student("Imran", "Ranchi"), new Student("Kavya", "Khunti"), new Student("Bittu", "Ramgarh"), new Student("Asha", "Ranchi"));8 Map<String, List<String>> byCity = new TreeMap<>();9 for (Student s : all) byCity.computeIfAbsent(s.city(), k -> new ArrayList<>()).add(s.name());10 for (Map.Entry<String, List<String>> e : byCity.entrySet()) {11 Collections.sort(e.getValue());12 System.out.println(e.getKey() + " (" + e.getValue().size() + "): " + e.getValue());13 }14 }15}
1import java.util.*;23public class Stock {4 static Map<String, Integer> stock = new TreeMap<>();5 static void purchase(String item, int q) { stock.merge(item, q, Integer::sum); }6 static void sell(String item, int q) {7 int have = stock.getOrDefault(item, 0);8 if (q > have) { System.out.println("Cannot sell " + q + " " + item + " (have " + have + ")"); return; }9 stock.put(item, have - q);10 }11 public static void main(String[] args) {12 purchase("Rice kg", 50); purchase("Sugar kg", 20); purchase("Salt pkt", 10);13 sell("Rice kg", 47); sell("Sugar kg", 8); sell("Salt pkt", 12); sell("Tea pkt", 1);14 purchase("Sugar kg", 5);15 System.out.println("Stock: " + stock);16 stock.forEach((k, v) -> { if (v < 5) System.out.println("LOW: " + k + " only " + v); });17 }18}
1import java.util.*;23record Result(String name, int total, int maths) { }45public class MeritTie {6 public static void main(String[] args) {7 List<Result> r = new ArrayList<>(List.of(new Result("Asha", 472, 95), new Result("Binod", 488, 99), new Result("Chetan", 472, 98),8 new Result("Diya", 488, 99), new Result("Eshan", 455, 90)));9 r.sort(Comparator.comparingInt(Result::total).reversed()10 .thenComparing(Comparator.comparingInt(Result::maths).reversed())11 .thenComparing(Result::name));12 int rank = 0;13 for (int i = 0; i < r.size(); i++) {14 Result x = r.get(i);15 boolean tie = i > 0 && x.total() == r.get(i - 1).total() && x.maths() == r.get(i - 1).maths();16 if (!tie) rank = i + 1;17 System.out.printf("%d. %-7s %d (maths %d)%n", rank, x.name(), x.total(), x.maths());18 }19 }20}
1import java.util.*;23public class Chart {4 static Map<String, TreeMap<Integer, String>> chart = new TreeMap<>();5 static void book(String coach, int seat, String name) {6 String old = chart.computeIfAbsent(coach, k -> new TreeMap<>()).putIfAbsent(seat, name);7 System.out.println(old == null ? "Booked " + coach + "-" + seat + " " + name : "X " + coach + "-" + seat + " taken by " + old);8 }9 static void cancel(String coach, int seat) {10 String n = chart.getOrDefault(coach, new TreeMap<>()).remove(seat);11 System.out.println(n == null ? "Nothing to cancel" : "Cancelled " + coach + "-" + seat + " (" + n + ")");12 }13 public static void main(String[] args) {14 book("S2", 14, "Anil"); book("S1", 3, "Rekha"); book("S2", 9, "Faizan"); book("S2", 14, "Mona"); book("B1", 22, "Kiran");15 cancel("S2", 9); book("S2", 9, "Mona");16 for (Map.Entry<String, TreeMap<Integer, String>> c : chart.entrySet()) {17 System.out.println("Coach " + c.getKey() + " (" + c.getValue().size() + " booked): " + c.getValue());18 }19 }20}
1import java.util.*;23record Order(String city, String month, int amount) { }45public class SalesReport {6 public static void main(String[] args) {7 List<Order> orders = List.of(new Order("Ranchi", "Jan", 42000), new Order("Dhanbad", "Jan", 31000), new Order("Ranchi", "Feb", 51000),8 new Order("Bokaro", "Feb", 18000), new Order("Dhanbad", "Feb", 36000), new Order("Ranchi", "Jan", 9000), new Order("Bokaro", "Jan", 22000));9 Map<String, Integer> total = new TreeMap<>();10 Map<String, Map<String, Integer>> byMonth = new TreeMap<>();11 for (Order o : orders) {12 total.merge(o.city(), o.amount(), Integer::sum);13 byMonth.computeIfAbsent(o.city(), k -> new TreeMap<>()).merge(o.month(), o.amount(), Integer::sum);14 }15 for (String city : total.keySet()) {16 Map.Entry<String, Integer> best = Collections.max(byMonth.get(city).entrySet(), Map.Entry.comparingByValue());17 System.out.printf("%-8s Rs %,7d best %s (Rs %,d)%n", city, total.get(city), best.getKey(), best.getValue());18 }19 List<Map.Entry<String, Integer>> rank = new ArrayList<>(total.entrySet());20 rank.sort(Map.Entry.<String, Integer>comparingByValue().reversed());21 System.out.println("Top 2: " + rank.subList(0, 2));22 }23}
put, get, getOrDefault, containsKey, remove, keySet, valuesentrySet() or forEach((k, v) -> ...)merge(k, 1, Integer::sum); group with computeIfAbsentcompareTocomparing, reversed, thenComparingmap.put("A", 1); map.put("A", 2); map size?
map.get("missing") returns...
Which map keeps keys sorted?
groupingBy| Old way | Lambda |
|---|---|
new Comparator<P>() { public int compare(P a, P b) { return a.price - b.price; } } | (a, b) -> a.price - b.price |
new Runnable() { public void run() { System.out.println("Hi"); } } | () -> System.out.println("Hi") |
(params) -> expression is a compact way to pass behaviour as a value. It implements a functional interface (one abstract method, Module 12).x -> x * 2() -> 42{ ...; return r; }(int a, int b) is optional1import java.util.function.*;23public class Main {4 public static void main(String[] args) {5 Predicate<Integer> isPass = m -> m >= 33; // test -> boolean6 Function<Double, Double> withGst = p -> p * 1.18; // input -> output7 Consumer<String> sms = msg -> System.out.println("SMS: " + msg); // use, no result8 Supplier<String> otp = () -> "OTP " + (100000 + 47219); // no input -> value9 BiFunction<Integer, Integer, Integer> area = (l, b) -> l * b;1011 System.out.println(isPass.test(45) + " " + isPass.negate().test(45));12 System.out.println(withGst.apply(1000.0));13 sms.accept("Your order is out for delivery");14 System.out.println(otp.get());15 System.out.println(area.apply(12, 10));16 Function<Double, Double> discount = p -> p * 0.9;17 System.out.println(discount.andThen(withGst).apply(1000.0)); // chain18 }19}
java.util.function has ready functional interfaces, so you rarely write your own. Each has one method: test, apply, accept, get. They can be combined: negate(), andThen().| Interface | Shape |
|---|---|
| Predicate<T> | T -> boolean |
| Function<T,R> | T -> R |
| Consumer<T> | T -> nothing |
| Supplier<T> | nothing -> T |
1import java.util.*;23public class Main {4 static boolean isLong(String s) { return s.length() > 6; }56 public static void main(String[] args) {7 List<String> cities = new ArrayList<>(List.of("ranchi", "dumka", "jamshedpur", "giridih", "deoghar"));8 cities.replaceAll(String::toUpperCase); // same as s -> s.toUpperCase()9 cities.forEach(System.out::println); // same as s -> System.out.println(s)10 cities.removeIf(Main::isLong); // static method of our class11 cities.sort(Comparator.comparing(String::length));12 System.out.println(cities);13 }14}
Class::method instead. Four forms: String::toUpperCase (on the item), Main::isLong (static), System.out::println (on an object), ArrayList::new (constructor).1// loop: 6 lines2List<Integer> big = new ArrayList<>();3for (Order o : orders)4 if (o.city().equals("Ranchi")) big.add(o.amount());5Collections.sort(big, Collections.reverseOrder());67// stream: 1 statement8List<Integer> big = orders.stream()9 .filter(o -> o.city().equals("Ranchi"))10 .map(Order::amount)11 .sorted(Comparator.reverseOrder())12 .toList();
| Intermediate | Terminal |
|---|---|
| filter, map, sorted | toList, collect |
| distinct, limit, skip | count, sum, average |
| returns a Stream | returns a result |
1import java.util.*;23record Product(String name, String category, int price, double rating) { }45public class Main {6 public static void main(String[] args) {7 List<Product> all = List.of(8 new Product("Kurta", "Fashion", 899, 4.1), new Product("Earbuds", "Electronics", 1499, 4.3),9 new Product("Saree", "Fashion", 2499, 4.6), new Product("Power bank", "Electronics", 999, 4.4),10 new Product("Jacket", "Fashion", 1999, 3.9), new Product("Smart watch", "Electronics", 2999, 4.0));1112 List<String> goodFashion = all.stream()13 .filter(p -> p.category().equals("Fashion"))14 .filter(p -> p.rating() >= 4.0)15 .sorted(Comparator.comparingInt(Product::price))16 .map(p -> p.name() + " Rs " + p.price())17 .toList();18 System.out.println(goodFashion);1920 List<String> top2 = all.stream()21 .sorted(Comparator.comparingDouble(Product::rating).reversed())22 .limit(2)23 .map(Product::name)24 .toList();25 System.out.println("Top rated: " + top2);26 }27}
filter keeps items that pass a test, map changes each item into something else, sorted orders them, limit(n) keeps the first n, toList() collects the result.marks stays unchanged; the final .toList() would give [96, 83, 71].1import java.util.*;2import java.util.stream.*;34record Order(String city, int amount) { }56public class Main {7 public static void main(String[] args) {8 List<Order> orders = List.of(new Order("Ranchi", 450), new Order("Dhanbad", 900), new Order("Ranchi", 1200),9 new Order("Bokaro", 300), new Order("Ranchi", 300));10 long ranchiCount = orders.stream().filter(o -> o.city().equals("Ranchi")).count();11 int total = orders.stream().mapToInt(Order::amount).sum();12 double avg = orders.stream().mapToInt(Order::amount).average().orElse(0);13 Optional<Order> biggest = orders.stream().max(Comparator.comparingInt(Order::amount));14 boolean anyBig = orders.stream().anyMatch(o -> o.amount() > 1000);15 IntSummaryStatistics st = orders.stream().mapToInt(Order::amount).summaryStatistics();1617 System.out.println("Ranchi orders: " + ranchiCount + ", total Rs " + total + ", avg Rs " + avg);18 System.out.println("Biggest: " + biggest.get() + ", any above 1000? " + anyBig);19 System.out.println(st);20 System.out.println(IntStream.rangeClosed(1, 5).map(x -> x * x).boxed().toList());21 }22}
mapToInt turns objects into numbers so you can call sum(), average(), max(). Optional wraps a result that may be missing: use orElse. anyMatch/allMatch answer yes/no questions.1import java.util.*;2import java.util.stream.*;34record Student(String name, String city, int marks) { }56public class Main {7 public static void main(String[] args) {8 List<Student> s = List.of(new Student("Aman", "Ranchi", 78), new Student("Pooja", "Ramgarh", 91), new Student("Imran", "Ranchi", 64),9 new Student("Kavya", "Khunti", 88), new Student("Bittu", "Ramgarh", 55), new Student("Asha", "Ranchi", 95));1011 Map<String, Long> perCity = s.stream().collect(Collectors.groupingBy(Student::city, TreeMap::new, Collectors.counting()));12 Map<String, Double> avgCity = s.stream().collect(Collectors.groupingBy(Student::city, TreeMap::new, Collectors.averagingInt(Student::marks)));13 Map<Boolean, List<String>> pass = s.stream().collect(Collectors.partitioningBy(x -> x.marks() >= 75,14 Collectors.mapping(Student::name, Collectors.toList())));15 String names = s.stream().map(Student::name).sorted().collect(Collectors.joining(", ", "[", "]"));1617 System.out.println("Count: " + perCity);18 System.out.println("Average: " + avgCity);19 System.out.println("75+: " + pass.get(true) + " below: " + pass.get(false));20 System.out.println("All: " + names);21 }22}
collect(Collectors.xxx) builds complex results. groupingBy = "per category" reports, partitioningBy = split in two, joining = one String, counting/averagingInt = numbers per group.java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).1import java.util.*;2import java.util.function.*;34public class LambdaCalc {5 public static void main(String[] args) {6 Map<String, BinaryOperator<Double>> ops = new LinkedHashMap<>();7 ops.put("+", (a, b) -> a + b);8 ops.put("-", (a, b) -> a - b);9 ops.put("*", (a, b) -> a * b);10 ops.put("/", (a, b) -> a / b);11 ops.put("^", Math::pow);12 ops.forEach((sym, f) -> System.out.println("12 " + sym + " 4 = " + f.apply(12.0, 4.0)));13 }14}
1import java.util.*;2import java.util.stream.*;34public class EvenSquares {5 public static void main(String[] args) {6 List<Integer> sq = IntStream.rangeClosed(1, 15).filter(n -> n % 2 == 0).map(n -> n * n).boxed().toList();7 System.out.println(sq);8 System.out.println("Sum: " + sq.stream().mapToInt(Integer::intValue).sum());9 }10}
1import java.util.*;2import java.util.stream.*;34public class Names {5 public static void main(String[] args) {6 List<String> raw = List.of(" aditi ", "RAHUL", "aditi", "sneha ", "Rahul");7 String out = raw.stream()8 .map(String::trim)9 .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase())10 .distinct()11 .sorted()12 .collect(Collectors.joining(", "));13 System.out.println(out);14 }15}
1import java.util.*;2import java.util.function.*;34record Product(String name, String cat, int price, double rating) { }56public class Search {7 public static void main(String[] args) {8 List<Product> all = List.of(new Product("Earbuds", "Audio", 1499, 4.3), new Product("Speaker", "Audio", 2499, 4.5), new Product("Headphones", "Audio", 999, 3.8),9 new Product("Soundbar", "Audio", 6999, 4.4), new Product("Mouse", "PC", 499, 4.2));10 Predicate<Product> audio = p -> p.cat().equals("Audio");11 Predicate<Product> budget = p -> p.price() <= 3000;12 Predicate<Product> good = p -> p.rating() >= 4.0;13 all.stream().filter(audio.and(budget).and(good))14 .sorted(Comparator.comparingInt(Product::price))15 .forEach(p -> System.out.println(p.name() + " Rs " + p.price() + " *" + p.rating()));16 }17}
1import java.util.*;2import java.util.stream.*;34record Student(String name, int marks) {5 String grade() { return marks >= 90 ? "A+" : marks >= 75 ? "A" : marks >= 33 ? "B" : "F"; }6}78public class Summary {9 public static void main(String[] args) {10 List<Student> c = List.of(new Student("Aman", 78), new Student("Bina", 95), new Student("Chirag", 28), new Student("Diya", 88), new Student("Eshan", 61));11 System.out.println("Passed: " + c.stream().filter(s -> s.marks() >= 33).count());12 System.out.printf("Average: %.1f%n", c.stream().mapToInt(Student::marks).average().orElse(0));13 System.out.println("Topper: " + c.stream().max(Comparator.comparingInt(Student::marks)).get().name());14 Map<String, List<String>> byGrade = c.stream().collect(Collectors.groupingBy(Student::grade, TreeMap::new, Collectors.mapping(Student::name, Collectors.toList())));15 System.out.println(byGrade);16 }17}
1import java.util.*;2import java.util.stream.*;34record Order(String city, String dish, int amount) { }56public class Analytics {7 public static void main(String[] args) {8 List<Order> o = List.of(new Order("Ranchi", "Litti Chokha", 180), new Order("Ranchi", "Biryani", 320), new Order("Dhanbad", "Litti Chokha", 160),9 new Order("Ranchi", "Litti Chokha", 200), new Order("Bokaro", "Momos", 120), new Order("Dhanbad", "Biryani", 300));10 System.out.println("Revenue: " + o.stream().collect(Collectors.groupingBy(Order::city, TreeMap::new, Collectors.summingInt(Order::amount))));11 Map<String, Long> dishCount = o.stream().collect(Collectors.groupingBy(Order::dish, Collectors.counting()));12 String top = dishCount.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey();13 System.out.println("Top dish: " + top + " (" + dishCount.get(top) + " orders)");14 System.out.printf("Average order: Rs %.2f%n", o.stream().mapToInt(Order::amount).average().orElse(0));15 }16}
1import java.util.*;2import java.util.stream.*;34public class TopWords {5 public static void main(String[] args) {6 String text = "Ranchi is green. Ranchi has waterfalls, and the waterfalls of Ranchi are famous. The city is calm and the people are kind.";7 Map<String, Long> freq = Arrays.stream(text.toLowerCase().replaceAll("[^a-z ]", "").split("\\s+"))8 .filter(w -> w.length() > 2)9 .collect(Collectors.groupingBy(w -> w, Collectors.counting()));10 freq.entrySet().stream()11 .sorted(Map.Entry.<String, Long>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))12 .limit(5)13 .forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));14 }15}
1import java.util.*;2import java.util.stream.*;34record Emp(String name, String dept, int salary) { }56public class HrReport {7 public static void main(String[] args) {8 List<Emp> e = List.of(new Emp("Asha", "IT", 72000), new Emp("Binod", "Sales", 41000), new Emp("Chhaya", "IT", 88000),9 new Emp("Dinesh", "HR", 39000), new Emp("Esha", "Sales", 52000), new Emp("Farhan", "IT", 65000));10 Map<String, List<Emp>> byDept = e.stream().collect(Collectors.groupingBy(Emp::dept, TreeMap::new, Collectors.toList()));11 byDept.forEach((d, list) -> {12 double avg = list.stream().mapToInt(Emp::salary).average().orElse(0);13 Emp top = list.stream().max(Comparator.comparingInt(Emp::salary)).get();14 String names = list.stream().map(Emp::name).collect(Collectors.joining(","));15 System.out.printf("%-5s %d staff, avg %,.0f, top %s [%s]%n", d, list.size(), avg, top.name(), names);16 });17 System.out.println(e.stream().mapToInt(Emp::salary).summaryStatistics());18 }19}
1import java.util.*;2import java.util.stream.*;34record Booking(String train, String cls, int fare, String status) { }56public class RailAnalytics {7 public static void main(String[] args) {8 List<Booking> b = List.of(new Booking("Rajdhani", "3A", 2850, "CNF"), new Booking("Rajdhani", "2A", 4100, "CNF"), new Booking("Garib Rath", "3A", 1350, "WL"),9 new Booking("Hatia-Patna", "SL", 380, "CNF"), new Booking("Hatia-Patna", "SL", 380, "WL"), new Booking("Rajdhani", "3A", 2850, "CNF"),10 new Booking("Hatia-Patna", "3A", 1020, "CNF"), new Booking("Garib Rath", "3A", 1350, "CNF"));11 System.out.println("Revenue (CNF): " + b.stream().filter(x -> x.status().equals("CNF"))12 .collect(Collectors.groupingBy(Booking::cls, TreeMap::new, Collectors.summingInt(Booking::fare))));13 Map.Entry<String, Long> busy = b.stream().collect(Collectors.groupingBy(Booking::train, Collectors.counting()))14 .entrySet().stream().max(Map.Entry.comparingByValue()).get();15 System.out.println("Busiest: " + busy.getKey() + " (" + busy.getValue() + ")");16 Map<Boolean, Long> cnf = b.stream().collect(Collectors.partitioningBy(x -> x.status().equals("CNF"), Collectors.counting()));17 System.out.println("Confirmed " + cnf.get(true) + ", waitlisted " + cnf.get(false));18 System.out.println("Fare bands: " + b.stream().collect(Collectors.groupingBy(x -> x.fare() < 1000 ? "budget" : x.fare() < 3000 ? "mid" : "premium", TreeMap::new, Collectors.counting())));19 }20}
iterate can be infinite; peek shows which elements are actually processed; limit stops early.1import java.util.*;2import java.util.stream.*;34public class LazyPrimes {5 static boolean isPrime(int n) {6 if (n < 2) return false;7 for (int d = 2; d * d <= n; d++) if (n % d == 0) return false;8 return true;9 }10 public static void main(String[] args) {11 int[] checked = {0};12 List<Integer> r = Stream.iterate(2, n -> n + 1)13 .peek(n -> checked[0]++)14 .filter(n -> n % 10 == 7)15 .filter(LazyPrimes::isPrime)16 .limit(10)17 .toList();18 System.out.println(r);19 System.out.println("Numbers examined: " + checked[0] + " (the stream stopped as soon as it had 10)");20 }21}
(params) -> body implements a functional interfaceString::length, System.out::printlnlist.stream().filter(...) changes the original list?
Which is a terminal operation?
s -> s.toUpperCase() as a method reference is...
You finished Collections, Generics & Streams: 4 modules and 40 practice examples.
D:\java-practice\part4java -versionD:\java-practicejava Main.java