Streams API allows processing sequential and parallel operations on elements of a stream. It provides intermediate operations that are lazy evaluated, and terminal operations that initiate stream processing. Common uses of Streams API include summing values, finding maximum/minimum values, filtering collections, mapping properties, and grouping/counting elements.
Java Streams Interview short reminder with examples
1. 1 #####################################################################################
2 #Stream
3 #####################################################################################
4
5 Explain when we use Streams API ?
6
7 Stream is a sequence of objects or primitive types.
8 Operations can be performed on the elements sequentially or in parallel.
9
10 Streams collectors support parallelism even over collections that arent thread-
safe.
11 The way they do this is to have each thread operate independently on its own
collection of intermediate results.
12
13 When a stream is executed in parallel, the map operation processes elements of
the stream.
14 Consequently, the ORDER in which the lambda expression e -> { parallelStorage.add
(e); return e; }
15 adds elements to the List parallelStorage can vary every time the code is run.
16
17 Warnings:
18 Make sure lambda expression parameters in stream operations are not stateful!
19 Do not modify that same list while you are iterating.
20
21 What are Streams lifecycles ?
22
23 creation from:
24 Collection,Array,IO Channel
25 intermediate operations : (The intermediate operations are not evaluated till a
terminal operation is called)
26 filter,flatMap,distinct,peek,map
27 terminal operation:
28 forEach,count,collect,allMatch,anyMatch
29
30 How to sum values from 1 - 100 ?
31
32 IntStream.range(1, 100)
33 .reduce(0, Integer::sum);
34 //or use
35 IntStream.range(1, 100)
36 .sum();
37
38 How to get maximum value from Integer array ?
39
40 Integer[] a = {1, 3, 4, 6, 33, 1};
41
42 System.out.println(Arrays.stream(a)
43 .max(Integer::compareTo)
44 );
45 //OR
46 System.out.println(Arrays.stream(a)
47 .reduce(0,Integer::max)
48 );
49
50 How to get stream of objects ?
51
52 Stream.of(...);
53
54 How to copy strings from old list into a new list
55
56 List<String> oldItemList = new ArrayList<>();
57 List<String> newitemList = olditemList.stream().collect(Collectors.toList());
58
59 How to make a stream processing parallel ?
60
61 roster
62 .stream()
63 .parallelStream() //use with caution as it uses fork join pool, by default
it has one less threads as you have processors,
64 .filter(e -> e.getGender() == Person.Sex.MALE) // An intermediate
operation, such as filter, produces a new stream.
65 .forEach(e -> System.out.println(e.getName())); // terminal operation, such
as forEach, produces a non-stream result
2. 66
67 How to run the parallelStream() in a different thread pool ?
68
69 ForkJoinPool forkJoinPool = new ForkJoinPool(2);
70 CompletableFuture<List<Integer>> primes = CompletableFuture.supplyAsync(() ->
71 IntStream.range(1, 1_000_000)
72 .parallel()
73 .collect(toList()),
74 forkJoinPool
75 );
76
77 How to produce 1-10 stream ?
78
79 IntStream.range(1,10).stream()
80
81 How to check the result of Stream is not null ?
82
83 values.stream()
84 .filter(s -> s.equals("two"))
85 .findAny()
86 .ifPresent(s -> {throw new RuntimeException("not found");});
87
88 How to assign action when result of stream is null ?
89
90 String s = strings.stream()
91 .filter(e -> e.equals("3"))
92 .findAny()
93 .orElse(new String("3"));
94
95 How to find if the element is on the list ?
96
97 List<String> genre = new ArrayList<String>(Arrays.asList("rock", "pop", "jazz",
"reggae","pop"));
98 genre.stream().allMatch(s -> !s.isEmpty()); //all must match
99 genre.stream().anyMatch(s -> s.indexOf("r") == 0); //at least 1 must match
100 System.out.println(genre.stream().distinct().count()); // prints 4
101 genre.stream().map(String::toUpperCase).forEach(System.out::println); //prints
each element in Uppercase
102
103 How to print out a map collection?
104
105 Map<String, List<String>> artists = new HashMap<String, List<String>>();
106 artists.put("rock", new ArrayList<String>(Arrays.asList("rockArtistA",
"rockArtistB")));
107 artists.put("pop", new ArrayList<String>(Arrays.asList("popArtistA", "popArtistB"
)));
108 genre.stream().flatMap(s -> artists.get(s).stream()).forEach(s -> System.out.
print(" " + s));
109 // prints rockArtistA rockArtistB popArtistA popArtistB
110
111 How to group map collection by map key?
112
113 public Map<Region.Wojewodztwo, List<Region>> groupSubregionByWojewodztwo() {
114 List<Region> list = Region.RegionRepository.bezrobocie2014();
115 return list.stream().collect(Collectors.groupingBy(e -> e.getWojewodztwo()));
116 }
117
118 How to group map collection by map key?
119
120 public String print£ódzkieRegions() {
121 List<Region> list = Region.RegionRepository.bezrobocie2014();
122 return
123 list.stream()
124 .filter(e -> e.getWojewodztwo().equals(Region.Wojewodztwo.
£ÓDZKIE))
125 .map(e -> e.getNazwa())
126 .peek(System.out::println)
127 .collect(Collectors.joining(" i ", "Podregiony ³ódzkie to: ",
"."));
128 //connects all values into 1 string with PREFIX and SUFIX
129 }
130
131 How to compare all values in stream using custom comparison function?
3. 132
133 public Region getRegionWithLowestStopaBezrobocia() {
134 List<Region> list = Region.RegionRepository.bezrobocie2014();
135 return list
136 .stream()
137 .reduce((a, b) -> a.getStopaBezrobocia() > b.getStopaBezrobocia()?b:a)
138 .get();
139 }
140
141 How to split a string using regex pattern
142
143 Pattern.compile(":")
144 .splitAsStream("foobar:foo:bar")
145 .filter(s -> s.contains("bar"))
146 .sorted()
147 .collect(Collectors.joining(":"));
148 // => bar:foobar
149
150 // or alternatively
151 Pattern pattern = Pattern.compile(".*@gmail.com");
152 Stream.of("bob@gmail.com", "alice@hotmail.com")
153 .filter(pattern.asPredicate())
154 .count();
155 // => 1
156
157 How to list files in current directory
158
159 try (Stream<Path> stream = Files.list(Paths.get(""))) {
160 String joined = stream
161 .map(String::valueOf)
162 .filter(path -> !path.startsWith("."))
163 .sorted()
164 .collect(Collectors.joining("; "));
165 System.out.println("List: " + joined);
166 } //must use try with resource to explicitly close directory stream
167
168 How to print a file
169
170 try (Stream<String> stream = Files.lines(Paths.get("res/nashorn1.js"))) {
171 stream
172 .filter(line -> line.contains("print"))
173 .map(String::trim)
174 .forEach(System.out::println);
175 }
176
177 //OR
178 Path path = Paths.get("res/nashorn1.js");
179 try (BufferedReader reader = Files.newBufferedReader(path)) {
180 long countPrints = reader
181 .lines()
182 .filter(line -> line.contains("print"))
183 .count();
184 System.out.println(countPrints);
185 }
186
187 How to sum all properties ?
188
189 ships.stream().mapToInt(ss -> ss.getSunk()).sum()
190
191 How to Count on objects with group by id?
192
193 list.stream()
194 .collect(Collectors.groupingBy(foo -> foo.id, Collectors.counting()))
195 .forEach((id,count)->System.out.println(id+"t"+count));
196
197 How to Sum on objects property with group by id?
198
199 list.stream()
200 .collect(Collectors.groupingBy(foo -> foo.id,
201 Collectors.summingInt(foo->foo.targetCost)))
202 .forEach((id,sumTargetCost)->System.out.println(id+"t"+sumTargetCost));
203