A Beginner’ Guide — JAVA 8 Streams

So.. Should I use Streams?

// for loop
for(int i = 0; i < list.size(); i++){
if(list.get(i) < 2){
list.remove(i);
} else {
list.set(i, list.get(i) * 2);
}
}
// stream
list2 = list2.stream()
.filter(n -> n > 1)
.map(n -> n * 2)
.collect(Collectors.toList());

Types of Stream Operations

Code Implementations

List<Integer> list = new ArrayList<>(Arrays.asList(5, 4, 3, 2, 1));List<Integer> result = list.stream() // reads List into a stream
.sorted()
.filter(n -> n > 1)
.map(n -> n * 2)
.distinct()
.limit(2)
.collect(Collectors.toList());
// result -> [4, 6]
List<Integer> list = new ArrayList<>(Arrays.asList(5,4,3,2,1));// checks if all elements are smaller than 6
boolean isAllMatch = list.stream()
.allMatch(n -> n < 6);
// returns true
// checks if any elements has length > 20
List<String> words= new ArrayList<>(Arrays.asList("hello","world"));
boolean isAnyMatch = words.stream()
.anyMatch(n -> n.length > 20);
// returns false
List<Integer> list = new ArrayList<>();
Optional<Integer> findAny = list.stream().findAny();
System.out.println(findAny.isPresent()); // prints false
List<Integer> list = new ArrayList<>(Arrays.asList(5,4,3,2,1));#1
Optional<Integer> minImpl1 = list.stream()
.min((a,b) -> a.compareTo(b));
#2
Optional<Integer> minImpl2 = list.stream()
.min((a,b) -> {
return a < b ? -1 : (a == b) ? 0 : 1
});
List<Integer> list = new ArrayList<>(Arrays.asList(5,4,3,2,1));Optional<Integer> reduce = list.stream()
.reduce((val, combVal) -> {
return combVal + val;
});
// computes sum of all values in the list
List<Integer> list = new ArrayList<>(Arrays.asList(5,4,3,2,1));// stream API implementation
list.stream().forEach(num-> System.out.print(num));
// list API implementation
list.forEach(num -> {
System.out.print(num);
});

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store