Java 8 stream Examples

Java Stream doesn’t store data, it operates on the source data structure (collection and array) and produce pipelined data that we can use and perform specific operations. Such as we can create a stream from the list and filter it based on a condition.Java 8 Stream support sequential as well as parallel processing, parallel processing can be very helpful in achieving high performance for large collections.

Java 8 Streams Examples

  • printing using IntStream
1
2
3
4
5
6
7
8
9
package com.tachyon.basic;

import java.util.stream.IntStream;

public class Java8 {
	public static void main(String []args){
		IntStream.range(1,10).forEach(i -> System.out.print(i+" "));
	}
}
  • printing with skip elements
1
2
3
4
5
6
7
8
9
package com.tachyon.basic;

import java.util.stream.IntStream;

public class Java8 {
	public static void main(String []args){
		IntStream.range(1,10).skip(5).forEach(i -> System.out.print(i+" "));
	}
}
  • sum using Integer Stream
1
2
3
4
5
6
7
8
9
10
package com.tachyon.basic;

import java.util.stream.IntStream;

public class Java8 {
	public static void main(String []args){
		int sum = IntStream.range(1,10).sum();
		System.out.println(sum);
	}
}
  • we can create Streams using Stream.of(arg) or .stream() method of java 8 sorted() , ifPresent() , findFirst(). here we are making stream of some strings and then sort them and print first element if present
1
2
3
4
5
6
7
8
9
10
11
package com.tachyon.basic;

import java.util.stream.Stream;

public class Java8 {
	public static void main(String []args){
		Stream.of("Shroud","Mortal","Dynamo")
		.sorted()
		.findFirst().ifPresent(System.out::println);
	}
}
  • filter() method is an operational method in stream . It is used to filter out elements based on some conditions. Here we are filtering names from array which starts with ‘S’ letter then printing the sorted order of elements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.tachyon.basic;

import java.util.Arrays;

public class Java8 {
	public static void main(String []args){
		String[] names = {"Street","Town","Shop","Treat"};
			Arrays.stream(names)
			.filter(i -> i.startsWith("S"))
			.sorted()
			.forEach(System.out::println);
	}
}
  • map() method is used to transforming one element to another by applying a function.Here we are mapping each element to its square and then printing the average value.
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.tachyon.basic;

import java.util.Arrays;

public class Java8 {
	public static void main(String []args){
		int[] numbers = new int[]{2,4,7,9};
		Arrays.stream(numbers)
		.map(i -> i*i).average()
		.ifPresent(System.out::print);
	}
}

Simple Example for map() , filter() and collect() methods

collect() is used to store the data source. It is a terminal operation.

Here we are mapping each String to Integer from String array using map() method then we are filtering only even numbers from them . After filtering we collect and store the data in List of Integers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.tachyon.basic;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8 {
	public static void main(String []args){
		String[] numbers = {"12","1","21","34","29","18"};
		List<Integer> nums = Arrays.stream(numbers)
							.map(i -> Integer.valueOf(i))
							.filter(i -> i%2==0)
							.collect(Collectors.toList());
		nums.forEach(i-> System.out.print(i+" "));

	}
}

Streams can be used to collect important data from a file. We can use various filters and map to collect information from the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void fileUsingStreams(String fileName) throws IOException {
		Stream<String> fileStream = Files.lines(Paths.get(fileName));
		
		// filter the list and print in sorted order
		fileStream.sorted().filter(i -> i.length() > 10)
		.forEach(System.out::println);
		
		
		// using collect method to convert the desired stream into a List
		List<String> wordList = Files.lines(Paths.get(fileName))
				.filter(x -> x.contains("wtf"))
				.sorted()
				.collect(Collectors.toList());
		
		wordList.forEach(x -> System.out.print(x+" "));
		
	}

Comments