Skip to content

Commit b90028d

Browse files
committed
feat(streams-api): add CollectorsDemo showcasing advanced collectors usage
What - Introduced `CollectorsDemo` class demonstrating practical use-cases of the Java Streams API and Collectors. - Added multiple examples: 1. Grouping elements by string length. 2. Counting word occurrences in a sentence. 3. Partitioning numbers into even/odd. 4. Summing values from a map. 5. Creating maps with transformations (uppercase → length). 6. Counting frequency of words using `toMap` with merge function. - Each example annotated with input, logic, and expected result. Why - Collectors are central to data aggregation and transformation in modern Java applications. - Provides clear, practical demonstrations beyond simple `toList()` usage. - Helps developers understand declarative data processing vs imperative loops. Logic 1. **Grouping by length** - `Collectors.groupingBy(String::length)` → Map<Integer, List<String>> where key = length. - Example: ["Anna", "Bob", "Alexander"] → {3=[Bob], 4=[Anna], 9=[Alexander]}. 2. **Counting word occurrences** - Sentence split into words → grouped by word → count aggregated with `Collectors.counting()`. - Efficient for computing frequency tables. 3. **Partitioning numbers** - `Collectors.partitioningBy(x -> x % 2 == 0)` → splits into two lists: true = evens, false = odds. - Example: [1,2,3,4,5,6] → {true=[2,4,6], false=[1,3,5]}. 4. **Summing values** - Demonstrated two ways: - `reduce(Integer::sum)` for manual accumulation. - `Collectors.summingInt(x -> x)` for cleaner summation. - Example: {Apple=10, Banana=20, Orange=15} → 45. 5. **Creating a map with transformations** - `Collectors.toMap(keyMapper, valueMapper)` builds maps directly from streams. - Example: ["Apple", "Banana"] → {APPLE=5, BANANA=6}. 6. **Counting frequency using merge function** - `Collectors.toMap(k -> k, v -> 1, (x,y)->x+y)` handles duplicate keys by summing counts. - Example: ["apple","banana","apple"] → {apple=2, banana=1}. Real-life applications - **Analytics**: word frequency counters, log aggregations, grouping by attributes. - **Reporting systems**: partitioning datasets (active/inactive users, passed/failed tests). - **E-commerce apps**: summing cart values, grouping orders by customer, counting product sales. - **Data transformation pipelines**: converting raw text or collections into structured maps. Notes - `groupingBy` → flexible grouping by classifier function. - `partitioningBy` → boolean-based split, always returns two groups. - `toMap` requires merge function when duplicates exist. - `Collectors.summingInt` is cleaner and safer than manual reduce for summation. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent f4bd6c3 commit b90028d

File tree

2 files changed

+75
-112
lines changed

2 files changed

+75
-112
lines changed

JAVA8/JavaCollectorsAPI/src/CollectorsDemo.java

Lines changed: 0 additions & 112 deletions
This file was deleted.
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import java.util.*;
2+
import java.util.stream.Collectors;
3+
4+
public class CollectorsDemo {
5+
public static void main(String[] args) {
6+
/* Collectors is a utility class, provides a set of methods to create common collectors. */
7+
8+
/* Example 1: Collecting Names by Length
9+
l1.stream().collect(Collectors.groupingBy(String::length)):
10+
- Group names based on their length.
11+
- Key: length of string.
12+
- Value: list of names having that length.
13+
Input: ["Anna", "Bob", "Alexander", "Brian", "Alice"]
14+
Result: {3=[Bob], 4=[Anna], 5=[Brian, Alice], 9=[Alexander]} */
15+
List<String> l1 = Arrays.asList("Anna", "Bob", "Alexander", "Brian", "Alice");
16+
System.out.println(l1.stream().collect(Collectors.groupingBy(String::length)));
17+
18+
19+
/* Example 2: Counting Word Occurrences
20+
Arrays.stream(sentence.split(" ")).collect(Collectors.groupingBy(...)):
21+
- Key: unique word.
22+
- Value: how many times that word occurs.
23+
Input: "hello world hello java world"
24+
Result: {hello=2, world=2, java=1} */
25+
String sentence = "hello world hello java world";
26+
System.out.println(Arrays.stream(sentence.split(" ")).collect(Collectors.groupingBy(x -> x, Collectors.counting())));
27+
28+
29+
/* Example 3: Partitioning Even and Odd Numbers
30+
l2.stream().collect(Collectors.partitioningBy(x -> x % 2 == 0)):
31+
- Predicate: x % 2 == 0 (true for even, false for odd).
32+
- Splits elements into two groups:
33+
true → even numbers, false → odd numbers.
34+
Input: [1, 2, 3, 4, 5, 6]
35+
Result: {false=[1, 3, 5], true=[2, 4, 6]} */
36+
List<Integer> l2 = Arrays.asList(1, 2, 3, 4, 5, 6);
37+
System.out.println(l2.stream().collect(Collectors.partitioningBy(x -> x % 2 == 0)));
38+
39+
40+
/* Example 4: Summing Values in a Map
41+
items.values().stream().reduce(Integer::sum):
42+
- Reduce operation to sum values manually.
43+
items.values().stream().collect(Collectors.summingInt(x -> x)):
44+
- Built-in collector to sum integer values.
45+
Input Map: {Apple=10, Banana=20, Orange=15}
46+
Result: 45 */
47+
Map<String, Integer> items = new HashMap<>();
48+
items.put("Apple", 10);
49+
items.put("Banana", 20);
50+
items.put("Orange", 15);
51+
System.out.println(items.values().stream().reduce(Integer::sum));
52+
System.out.println(items.values().stream().collect(Collectors.summingInt(x -> x)));
53+
54+
55+
/* Example 5: Creating a Map from Stream Elements
56+
fruits.stream().collect(Collectors.toMap(...)):
57+
- Key: fruit name in uppercase (x -> x.toUpperCase()).
58+
- Value: length of fruit name (x -> x.length()).
59+
Input: ["Apple", "Banana", "Cherry"]
60+
Result: {APPLE=5, BANANA=6, CHERRY=6} */
61+
List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry");
62+
System.out.println(fruits.stream().collect(Collectors.toMap(x -> x.toUpperCase(), x -> x.length())));
63+
64+
65+
/* Case 2: Counting Frequency of Words
66+
words2.stream().collect(Collectors.toMap(...)):
67+
- Key: the word itself (k -> k).
68+
- Value: initial count = 1 (v -> 1).
69+
- Merge function: (x, y) -> x + y → sum frequencies.
70+
Input: ["apple", "banana", "apple", "orange", "banana", "apple"]
71+
Result: {apple=3, banana=2, orange=1} */
72+
List<String> words2 = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
73+
System.out.println(words2.stream().collect(Collectors.toMap(k -> k, v -> 1, (x, y) -> x + y)));
74+
}
75+
}

0 commit comments

Comments
 (0)