Stream Collectors

This time, I will show you how to use collectors along with streams to group by, concatenate, map, and list. Example: Convert a list of elements to a string separated by ‘,’ import java.util.List; import java.util.stream.Collectors; public class StreamToStringConverter { private String parse(){ return List.of("Java", "C++", "Lisp", "Haskell"). stream().collect(Collectors.joining(",")); } public static void main(String[] args){ var result = new StreamToStringConverter().parse(); assert "Java,C++,Lisp,Haskell".equals(result); } } From a list, generate another list selecting elements if the string length equals four. [Read More]

Stream Filters

A stream represents a sequence of elements and supports different operations to perform calculations in those elements: import java.util.List; import java.util.Arrays; import java.util.stream.Collectors; public class StringFilter { private List<String> parse(){ return Arrays.asList("Java", "C++", "Lisp", "Haskell"). stream().filter( p -> p.startsWith("J")).toList(); } public static void main(String[] args){ var result = new StringFilter().parse(); assert 1 == result.size(); assert "Java" == result.get(0); } } After creating a Stream of Strings, we filtered by those starting with the letter J. [Read More]

Streams

The stream interface is defined in the java.util.stream package. Since Java 8, the stream API will be used to process collections. Streams support aggregate operations. The common aggregate operations are filter, map, reduce, find, match, and sort. The map method maps each element to its corresponding result. The following Java code uses the map to get squares of numbers. import java.util.List; import java.util.Arrays; import java.util.ArrayList; import java.util.stream.Collectors; public class MapSquares { private List<Integer> square(List<Integer> numbers){ return numbers. [Read More]