Program to convert a Map to a Stream in Java

Java 8Object Oriented ProgrammingProgramming

At first, create a Map and set values −

Map<Integer, String> map = new HashMap<>();
map.put(1, "Kevin");
map.put(2, "Ryan");
map.put(3, "Nathan");
map.put(4, "Ricky");
map.put(5, "Shane");
map.put(6, "Adam");

Now, convert the Map to Stream −

Stream<Map.Entry<Integer, String> > stream = map.entrySet().stream();
System.out.println("Stream (Map to Stream) = "+ Arrays.toString(stream.toArray()));

Example

Following is the program to convert a Map to a Stream in Java −

import java.util.*;
import java.util.stream.*;
public class Demo {
   public static void main(String args[]) {
      Map<Integer, String> map = new HashMap<>();
      map.put(1, "Kevin");
      map.put(2, "Ryan");
      map.put(3, "Nathan");
      map.put(4, "Ricky");
      map.put(5, "Shane");
      map.put(6, "Adam");
      System.out.println("Map = " + map);
      Stream<Map.Entry<Integer, String> > stream = map.entrySet().stream();
      System.out.println("Stream (Map to Stream) = "+ Arrays.toString(stream.toArray()));
   }
}

Output

Map = {1=Kevin, 2=Ryan, 3=Nathan, 4=Ricky, 5=Shane, 6=Adam}
Stream (Map to Stream) = [1=Kevin, 2=Ryan, 3=Nathan, 4=Ricky, 5=Shane, 6=Adam]
raja
Published on 25-Sep-2019 07:39:14
Advertisements