-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamApi.java
More file actions
306 lines (255 loc) · 13 KB
/
StreamApi.java
File metadata and controls
306 lines (255 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
record Employee(int id, String name) {
}
record Employees(String name, String department, int salary) {
}
record EmployeesWithGender(String name, String department, String gender, int salary) {
}
record EmployeeSkills(String name, List<String> skills) {
}
void main() {
var list = Arrays.asList(2, 1, 6, 3, 4, 5, 5, 2, 8);
System.out.println("Question - 01 - Find the second largest number of a list");
list.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.limit(1)
.forEach(System.out::println);
System.out.println();
System.out.println("Question - 02 - Find out all the even numbers of a given list");
list.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
System.out.println();
System.out.println("Question - 06 - Find the average of a given list");
System.out.println(list.stream()
.mapToDouble(i -> i).average().getAsDouble());
System.out.println();
System.out.println("Question - 09 - Find all duplicates numbers of a list & Print them");
list.stream()
.filter(n -> Collections.frequency(list, n) > 1)
.distinct()
.forEach(System.out::println);
System.out.println();
System.out.println("Question - 10 - Find the square of the first three even numbers");
list.stream()
.sorted()
.filter(n -> n % 2 == 0)
.limit(3)
.map(n -> n * n)
.forEach(System.out::println);
System.out.println();
List<String> fruits = Arrays.asList("Apple", "Banana", "Guava", "cherry", "coconut", "Berry");
System.out.println("Question - 11 - Convert a list of string to upper case");
fruits.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
System.out.println();
System.out.println("Question - 12 - Concatenate all the string of a given list of string");
System.out.println(fruits.stream().collect(Collectors.joining(",")));
System.out.println();
System.out.println("Question - 13 - Count number of string which starts with a specific char");
System.out.println(fruits.stream().filter(s -> s.startsWith("B")).count());
System.out.println();
String str = "This is Java language and Java is versatile language ";
System.out.println("Question - 14 - Remove duplicate words of a given string");
Arrays.stream(str.split(" "))
.distinct()
.forEach(System.out::println);
System.out.println();
System.out.println("Question - 15 - Count words frequency in a given string");
var wordFreq = Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
System.out.println(wordFreq);
System.out.println();
System.out.println("Question - 16 - Group names by their first letter & count of each group");
String[] names = {"Anand", "Bipin", "Rakesh", "Abhi", "Rohan", "Akash", "Ravi", "Sima"};
Map<Character, Long> groupedByLetter = Arrays.stream(names)
.collect(Collectors.groupingBy(n -> n.charAt(0), Collectors.counting()));
System.out.println(groupedByLetter);
System.out.println();
System.out.println("Question - 17 - How do you merge 2 integer arrays into a sorted array");
int[] arr1 = {5, 3, 1};
int[] arr2 = {4, 2, 6};
int[] merged = IntStream.concat(Arrays.stream(arr1), Arrays.stream(arr2))
.sorted()
.toArray();
System.out.println(Arrays.toString(merged));
System.out.println();
System.out.println("Question - 18 - Concatenate two list of strings & remove duplicates");
List<String> list1 = Arrays.asList("Java", "Spring", "Docker");
List<String> list2 = Arrays.asList("Docker", "Kafka", "Java");
List<String> merged2 = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
System.out.println(merged2);
System.out.println();
System.out.println("Question - 19 - Filter all the palindrome words of a list using stream");
String[] palindrome = {"abc", "ada", "Kiran", "level", "apple", "narendra", "madam"};
Arrays.stream(palindrome)
.filter(w -> w.equals(new StringBuilder(w).reverse().toString()))
.forEach(System.out::println);
System.out.println();
System.out.println("Question - 20 - Partition a list of numbers into 2 groups: even and odd");
var partitioned = list.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(partitioned);
System.out.println();
System.out.println("Question - 21 - Sort a list of employees by employee id descending");
List<Employee> empList = Arrays.asList(
new Employee(123, "Narendra Sahoo"),
new Employee(456, "Abhay Parida"),
new Employee(876, "Dilip Singh"));
empList.stream()
.sorted(Comparator.comparing(Employee::id, Comparator.reverseOrder()))
.forEach(System.out::println);
System.out.println();
System.out.println("Question - 26 - How to sort a Map based on keys or values using stream?");
Map<String, Integer> map = new HashMap<>();
map.put("Utkarsh Yadav", 25);
map.put("Kiran Gupta", 21);
map.put("Gopal Rajpal", 45);
map.put("Hari", 65);
map.put("Ruhi", 2);
map.put("Manas", 44);
System.out.println("-- sorted by key --");
map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(System.out::println);
System.out.println("-- sorted by value --");
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(System.out::println);
System.out.println();
List<Employees> employees = List.of(
new Employees("Kiran", "HR", 60000),
new Employees("Ravi", "IT", 90000),
new Employees("Hari", "IT", 110000),
new Employees("Dilip", "HR", 70000),
new Employees("Mira", "Sales", 50000));
System.out.println("Question - 27 - How to group employees by their department");
Map<String, List<Employees>> grpByDept = employees.stream()
.collect(Collectors.groupingBy(Employees::department));
System.out.println(grpByDept);
System.out.println();
System.out.println("Question - 28 - Find the Average of Salaries in Each Department");
var avgByDept = employees.stream()
.collect(Collectors.groupingBy(Employees::department,
Collectors.averagingDouble(Employees::salary)));
System.out.println(avgByDept);
System.out.println();
System.out.println("Question - 29 - Sum the Salaries of Employees by Department");
var sumByDept = employees.stream()
.collect(Collectors.groupingBy(Employees::department,
Collectors.summingInt(Employees::salary)));
System.out.println(sumByDept);
System.out.println();
System.out.println("Question - 30 - Find the highest/lowest paid employee in each department");
System.out.println("-- highest --");
employees.stream()
.collect(Collectors.groupingBy(Employees::department,
Collectors.maxBy(Comparator.comparingInt(Employees::salary))))
.forEach((dept, emp) -> System.out.println(dept + " → " + emp.orElse(null)));
System.out.println("-- lowest --");
employees.stream()
.collect(Collectors.groupingBy(Employees::department,
Collectors.minBy(Comparator.comparingInt(Employees::salary))))
.forEach((dept, emp) -> System.out.println(dept + " → " + emp.orElse(null)));
System.out.println();
System.out.println("Question - 31 - How to group employees by department and then by gender");
List<EmployeesWithGender> employeesWithGenders = List.of(
new EmployeesWithGender("Kiran", "HR", "Female", 60000),
new EmployeesWithGender("Ravi", "IT", "Male", 90000),
new EmployeesWithGender("Hari", "IT", "Male", 110000),
new EmployeesWithGender("Dillip", "HR", "Male", 70000),
new EmployeesWithGender("Mira", "Sales", "Female", 50000));
var grpByDeptThenGender = employeesWithGenders.stream()
.collect(Collectors.groupingBy(EmployeesWithGender::department,
Collectors.groupingBy(EmployeesWithGender::gender)));
System.out.println(grpByDeptThenGender);
System.out.println();
System.out.println("Question - 32 - Group strings by their length");
var words = Arrays.asList("a", "bb", "Mira", "ccc", "dd", "eee", "f", "Sila", "Nita");
var byLength = words.stream().collect(Collectors.groupingBy(String::length));
System.out.println(byLength);
System.out.println();
System.out.println("Question - 33 - Count the occurrences of each word in a sentence");
String sentence = "this is a test this is only a test";
System.out.println(Arrays.stream(sentence.split(" "))
.collect(Collectors.groupingBy(s -> s, Collectors.counting())));
System.out.println();
System.out.println("Question - 34 - How to Reverse each word in a string");
String sentence2 = "hello world java";
System.out.println(
Arrays.stream(sentence2.split(" "))
.map(s -> new StringBuilder(s).reverse().toString())
.collect(Collectors.joining(" ")));
System.out.println();
System.out.println("Question - 35 - Count & find unique words across a list of paragraphs");
var paragraphs = Arrays.asList(
"Java is great",
"Streams are powerful",
"Flatmap is useful");
long totalWords = paragraphs.stream()
.flatMap(p -> Arrays.stream(p.split(" ")))
.count();
List<String> uniqueWords = paragraphs.stream()
.flatMap(p -> Arrays.stream(p.split(" ")))
.distinct()
.collect(Collectors.toList());
System.out.println("Total: " + totalWords + ", Unique: " + uniqueWords);
System.out.println();
System.out.println("Question - 36 - Find all unique skills from a list of employees");
List<EmployeeSkills> employeeSkills = Arrays.asList(
new EmployeeSkills("Dillip", Arrays.asList("Java", "Spring", "SQL")),
new EmployeeSkills("Kiran", Arrays.asList("Java", "React", "AWS")),
new EmployeeSkills("Ravi", Arrays.asList("Python", ".Net", "AWS")));
// approach 1 - map then flatMap
employeeSkills.stream()
.map(EmployeeSkills::skills)
.flatMap(Collection::stream)
.distinct()
.forEach(System.out::println);
// approach 2 - direct flatMap
Set<String> uniqueSkills = employeeSkills.stream()
.flatMap(e -> e.skills().stream())
.collect(Collectors.toSet());
System.out.println(uniqueSkills);
System.out.println();
// ─── Extra: Interview-critical operations ──────────────────────────────
System.out.println("EXTRA - 01 - reduce() — sum, product, max");
int sum = list.stream().reduce(0, Integer::sum);
int product = list.stream().reduce(1, (a, b) -> a * b);
Optional<Integer> maxVal = list.stream().reduce(Integer::max);
System.out.println("Sum: " + sum + ", Product: " + product + ", Max: " + maxVal.orElse(0));
System.out.println();
System.out.println("EXTRA - 02 - collect to Set / UnmodifiableList");
Set<Integer> asSet = list.stream().collect(Collectors.toSet());
List<Integer> unmodifiable = list.stream().collect(Collectors.toUnmodifiableList());
System.out.println("Set (no duplicates): " + asSet);
System.out.println("Unmodifiable list: " + unmodifiable);
System.out.println();
System.out.println("EXTRA - 03 - Optional — findFirst, min, max, ifPresent, orElse");
Optional<Integer> first = list.stream().filter(n -> n > 4).findFirst();
Optional<Integer> minVal = list.stream().min(Comparator.naturalOrder());
Optional<Integer> maxVal2 = list.stream().max(Comparator.naturalOrder());
first.ifPresent(v -> System.out.println("First > 4: " + v));
System.out.println("Min: " + minVal.orElse(-1));
System.out.println("Max: " + maxVal2.orElse(-1));
System.out.println();
System.out.println("EXTRA - 04 - anyMatch / allMatch / noneMatch");
System.out.println("Any > 7: " + list.stream().anyMatch(n -> n > 7));
System.out.println("All > 0: " + list.stream().allMatch(n -> n > 0));
System.out.println("None < 0: " + list.stream().noneMatch(n -> n < 0));
System.out.println();
System.out.println("EXTRA - 05 - mapToInt / mapToDouble / summaryStatistics");
IntSummaryStatistics stats = list.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
System.out.println("Count: " + stats.getCount());
System.out.println("Sum: " + stats.getSum());
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Avg: " + stats.getAverage());
System.out.println();
System.out.println("─── end ───");
}