Category: Java programming question
-
Remove Duplicates from a List by Field in Java
Assume an Employee class with an id field: Approach 1: Using toMap() (Keeps first occurrence) Approach 2: Using TreeSet with Comparator (Keeps first per comparator) Summary:
-
Merge Two Lists Using Streams
Approach 1 — Using Stream.concat Approach 2 — Using Stream.of + flatMap Explanation:
-
Sort a List of Objects by Multiple Fields
Approach 1 — thenComparing Approach 2 — Combined Lambda Comparator Explanation:
-
Sort a List of Objects by a Field
Approach 1 — Using Comparator.comparing Approach 2 — Using a Lambda Comparator Explanation:
-
Find the Shortest String in a List
Approach 1 — Using min with a Comparator Approach 2 — Sorting and Taking First Explanation:
-
Find the Longest String in a List
Approach 1 — Using max with a Comparator Approach 2 — Using reduce Pairwise Explanation:
-
Count the Frequency of Each Element in a List
Approach 1 — Using groupingBy and counting Approach 2 — Using toMap with a Merge Function Explanation:
-
Finding the Second-Largest Number in a List Using Java Streams
In many applications, you may need to identify the second-largest (or second-highest) number in a collection. Java Streams provide elegant and concise ways to achieve this with functional-style operations. Consider the example list: Notice that the list may contain duplicates, so we need to handle that to ensure correctness. Approach 1: Using distinct(), sorted(), and…
-
Partition a List into Even and Odd Numbers
Approach 1: Using Collectors.partitioningBy() Why it works: Approach 2: Using Collectors.toCollection (Alternative) Why it works:
-
Generate Random Numbers
Approach 1: Using Stream.generate() Why it works: Approach 2: Using Random.ints() (Alternative) Why it works:
