Common Mistakes I found in the intern developers: Part 5: Misuse of Java Stream

With the experience I got by working with software engineering interns, I noticed some of common mistakes and programming patterns.
Here I have listed down some of the common mistakes and bad practices which will be done by new software developers. Therefore this will help the new java developers to identify and correct their mistakes in the future.
This article is the fifth of the series.
- Stream filter and for each where collect method is possible
Example 1: Use the collect(…) method
List<String> filtered = new ArrayList<>();
input.stream()
.filter(String::isEmpty)//filter operation
.forEach(item -> filtered.add(item));//not to use foreach operation
//Proper wayList<String> filtered = input.stream()
.filter(String::isEmpty)//filter operation
.collect(Collectors.toList());
Most of the times new developers tend to declare collection variables outside and after the filter statement, go for a forEach and add items to the collection. This operation can be simply achieved using the collect operations
- Filter with possible null point exceptions
Let’s consider the same above example. There the collection input could be null as well (maybe coming as a parameter). Therefore, the above code will cause in null point exception if we are not handled it.
We can use the ofNullable(…) method to avoid such incidents. (or do a simple null check beforehand)
Optional.ofNullable(input).orElse(Collections.emptyList()).stram()....
- Not much use of map functions and flatMap functions
Although the filter method is used by new developers, the map and flatMap is rarely used. But using map and flatMap will make the code more readable and simpler syntax as well.
- Sorting and assignment to collections where sort order loses
If you want to sort the data, then collect using some collectors like toSet will remove the sort order (since the collector does not maintain the order or elements). Therefore always has to use LinkedHashSet like sets.
Example 2: Collect such that sort order remains
Optional.ofNullable(input)
.orElse(Collections.emptyList())
.stream()
.sorted()
.collect(Collectors.toCollection(LinkedHashSet::new));
- Not using the isPresent in filter get statements
Example 3: not using the isPresent method
input
.stream()
.filter(String::isEmpty)
.findAny()
.get(); //this shold be avoided
If the above code is executed and no match found for the input, invoking the get will result in NoSuchElementException. Therefore, we should always need to check is there a match using isPresent method. Or else we can simply use the orElse method with the default value if not matched. (Other alternatives is orElseGet(…) which can provide a supplier as an input)
Please leave a comment below if you have any questions or feedback.
If you like this post, follow me on Medium for more similar posts.
If you have any concerns or questions, please use the comment section below.