Java StJava Streams are a not a very known feature of Java to make it more functional programming language.
The benefits of using streams are:
- Make the code more delcarative , so it’s easier to undestand it
- Easier to paralelize using parallelStream instead of the basic Stream
The first step to use a filter is to apply it to an Iterable:
List<Integer> example = Arrays.asList(new Integer(1), new Integer(2), null);
example.stream();
Filter
One of the basic operations over a stream is to filter the values of it discarting the elements that don’t acomplish a constraint:
List<Integer> numbers = Arrays.asList(new Integer(1), new Integer(2), null);
// Remove null values
numbers.stream().filter(number->!=null).collect(Collectors.toList());
Map
Another basic operation over a stream is the map operation. This operation converts an element of the stream to another element using a function:
List<Integer> numbers = Arrays.asList(new Integer(1), new Integer(2), null);
// Double
List<Integer> doubles = numbers.stream().map(number->number*2).collect(Collectors.toList());
Also can be declared using the function
List<String> letters = Arrays.asList("a", "b", "c");
List<String capitals = numbers.stream().map(String::toUpperCase).collect(Collectors.toList());
forEach
Executes a function for each element of the stream:
List<String> words = Arrays.asList("hi","bye");
wordsstream().forEach(p -> System.out.println(p));
Collectors
The collectors can be used to convert the stream to diferent types. The more commons are:
List<String> words = Arrays.asList("hi "bye");
List<String> list= words.stream().collect(Collectors.toList());
Set<String> list= words.stream().collect(Collectors.toSet());
Extra methods
There are also extra methods like distinct that can be used to delete the repeated values :
List<String> words = Arrays.asList("repeated", "repeated", "non repeated");
List<String> nonRepeated = words.stream().distinct().collect(Collectors.toList());
Another useful opeation with streams is limit
List<String> words = Arrays.asList("repeated", "repeated", "non repeated");
List<String> oneWord = words.stream().limit(1).collect(Collectors.toList());