Stream Interface in Java 8

  • To leverage the use of Stream you need to understand how to convert any DataStructure into a Stream

In below example, we have converted all type of collection into Stream :

  • Arrays
  • List
  • Set
  • Map
public class Example {
	public static void main(String[] args) {
		//Array To Stream
		int[] x = {1,2,3};
		Arrays.stream(x).forEach(System.out::println);
		
		//You can provide Start and end index here
		Arrays.stream(x,0,x.length).forEach(System.out::println);
		
		Stream.of(x).forEach(System.out::println);//Does not take primitive type array
		
		List<String> stringList = Arrays.asList("Hello","World","This","Is","Heapwizard");
		stringList.stream().forEach(System.out::println);
		
		Set<String> stringSet = new HashSet<>(Arrays.asList("Hello","World","This","Is","Heapwizard"));
		stringSet.stream().forEach(System.out::println);
		
		Map<String, String> map = new HashMap<>();
		map.put("Hello", "World");
		map.put("Heap", "Wizard");
				
		map.entrySet().stream().forEach(System.out::println);
		map.entrySet().stream().map(Map.Entry::getKey).forEach(System.out::println);
		map.entrySet().stream().map(Map.Entry::getValue).forEach(System.out::println);
		map.keySet().stream().forEach(System.out::println);
		map.values().stream().forEach(System.out::println);
	}
}

Leave a Comment