Java stream operations and conversion with examples

Java 8 Stream tutorial 

Java 8 stream help to achieve functional programming in java and are introduced in java 8 stream need a source, intermediate operation and terminal operation. Stream use functional interface which help to implement lambdas please check out java functional interface.

  • Stream help to process bulk data in a fast and efficient way.
  • Stream doesn’t store any data in it.
  • It is not a data structure it process the input from a data source.
  • The Stream intermediate operation are lazily executed, and we can pipeline multiple intermediate operation together.

All java stream API class and interface are present in java.util.stream.

java8 stream operations

A source can be any data especially java collections, Lists, Sets. The stream class can be created in two ways either by using stream() or parallelStream() methods in java 8 collections. The parallelStream() methods create and operate on multiple threads at time just like parallel processing.


List<String> numbers = Arrays.asList("1", "2", "3");
numbers.stream().forEach(System.out::println);

Java Stream Operations

Intermediate operations return stream, so we can chain multiple intermediate operations together to perform sequence operation.

Terminal operation are final stage in stream operation where result are returned which can void or any non stream result.

All stream operations uses functional interfaces, so we can convert this functional interface into lambda expression to make code shorter and understandable. 

You can see that data source such as collection, list, set all can hold only objects for which stream can be created but how to create a stream for primitive datatype.

By using Stream.of() method we can create stream operation for primitive datatype alternative we can also use IntStream(for integer), DoubleStream(for double) to handle primitive datatype.

  
Stream.of(1, 2, 3).forEach(System.out::println);
IntStream.range(1, 5).forEach(System.out::println);
  
Java Stream  Conversion

We can convert object stream to primitive stream by using mapToInt() ,mapToDouble() and flatMapToInt() and flatMapToDouble() methods which will convert the object stream to primitive stream based on methods we are using if we use mapToInt() and flatMapToInt() it produces IntStream.

// Object to Primitive stream
IntStream primitivenumber = numbers.stream().mapToInt(Integer::valueOf);                
mapToObj() will convert primitive stream to object stream.
// Primitive to Object stream
List<String> numbers = IntStream.range(1, 5).mapToObj(i -> "n" + i).collect(Collectors.toList());    

Intermediate operations

filter() – take a predicate as parameter and return a single stream consisting of the result which pass the predicate passed.

Arrays.asList("11", "21", "31").stream().filter(n -> n.startsWith("1")).forEach(System.out::println);
// 11

map() – take a function as parameter then apply them to each input on stream. Map method perform transformation on stream input and return the transformed stream as output.

Arrays.asList("1", "2", "3").stream().map(n -> n + n).forEach(System.out::println);
//		11
//		22
//		33    

flatMap() – take a function as parameter, its same like map methods but flatmap perform transformation and flattening of stream. Flatmap perform flattening on stream of stream input and convert it to single stream output this is main difference between map and flatmap.

distinct() – return steam containing distinct values this method uses hashcode and equals methods internally to get the distinct element from the stream.

Arrays.asList("1", "2", "1").stream().distinct().forEach(System.out::println);
//1
//2                

sorted() – return sorted stream in natural order.

Arrays.asList("1", "3", "2").stream().sorted().forEach(System.out::println);
//		1
//		2
//		3

peek() – take consumer as parameter and perform given consumer function on them without returning anything this method mainly used in debugging in stream operation.

Arrays.asList("1", "2", "3").stream().peek(n -> System.out.println("Value = " + n)).map(n -> n + n).forEach(System.out::println);
//Value = 1
//11
//Value = 2
//22
//Value = 3
//33                

limit() - method is used to fetch only the given number of elements(first element to given n element) from the stream and return them as a stream. The given number should not be greater than the max size.

Arrays.asList("1", "3", "2").stream().limit(1).forEach(System.out::println);
// 1         

skip() - its opposite of limit() where skip() will skip the first to n given element from the stream and return a new stream containing element after a given n index. If given n is greater than max size than an empty stream is returned.

Arrays.asList("1", "3", "2").stream().skip(1).forEach(System.out::println);
// 3
// 2

Terminal operations

toArray() – convert stream into array and return it.

Arrays.asList(1, 2, 3).stream().map(n -> n + 1).toArray();        

count() - return the number of elements in the given stream.

Arrays.asList(1, 2, 3).stream().count();
//3

forEach() – mainly used to display the elements in stream and these methods take consumer as a parameter.

Arrays.asList(1, 2, 3).stream().map(n -> n + 1).forEach(System.out::println);
//3

min() – method is present in primitive stream such IntStream which is used to find the min value element in the stream.

IntStream.range(1, 5).min().getAsInt();
//1  

max() - method is present in primitive stream such IntStream which is used to find the max value element in the stream.

IntStream.range(1, 5).max().getAsInt();
//4     

anyMatch() – take predicate as parameter and check whether any elements in the given stream pass the predicate and return boolean.

Arrays.asList(1, 2, 3).stream().anyMatch(n -> n == 1);
//true

allMatch() – take predicate as parameter if all elements in stream pass the predicate return true otherwise return false.

Arrays.asList(1, 2, 3).stream().allMatch(n -> n != 1);
//false

noneMatch() – take predicate as parameter and just opposite of anymatch methods if any element passes the predicate then return false otherwise return true.

Arrays.asList(1, 2, 3).stream().noneMatch(n -> n != 1);
//false

findAny() - return an optional containing any element from the stream if the stream is empty then an empty optional is returned.

// Return Optional
System.out.println(Arrays.asList("s1", "n1", "s2").stream().filter(s -> s.startsWith("s")).findAny().get());
//s1

findFirst() – return an optional containing the first element in the stream and empty optional if stream is empty.

// Return Optional
Arrays.asList("s1", "n1", "s1").stream().filter(s -> s.startsWith("s1")).findFirst().get();
//s1        

If you have any comments 💭💭 please leave it below and I will answer it and if you have the best solution please let us know sharing is always best 💓.

Don't forget to share this post with your developer friends.😇😇

Post a Comment

Previous Post Next Post

Recent Posts

Facebook