January 19, 2024

Java Stream – Convert a Stream to Map

In this tutorial you’ll see how to convert a Stream to Map using collector method and utility methods like toMap() and groupingBy() of Collectors class in Java Stream API.

Syntax of toMap() method is as given below-

toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)

This method returns a Collector that accumulates elements into a Map. Both of the arguments passed to the method are of type Function which is a functional interface. Using these mapping functions keyMapper and valueMapper, keys and values of the resulting Map are calculated.

1. Using Collectors.toMap() method

In the following example a list of students is collected to a Map where key is the student’s roll number and value is Student name.

Student class used is-

public class Student {
  private int rollNo;
  private String name;
  private String stream;
  private int marks;
  Student(int rollNo, String name, String stream, int marks){
    this.rollNo = rollNo;
    this.name = name;
    this.stream = stream;
    this.marks = marks;
  }
  public int getRollNo() {
    return rollNo;
  }
  public String getName() {
    return name;
  }

  public String getStream() {
    return stream;
  }

  public int getMarks() {
    return marks;
  }

  @Override
  public String toString() {
    return "Roll Number: " +  getRollNo() 
        + " Name: " + getName() + " Marks: " + getMarks();
  }
}
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StreamToMap {

  public static void main(String[] args) {
    List<Student> studentList = Arrays.asList(new Student(1, "Mercy", "Science", 73),
              new Student(2, "Ram", "Science", 99),
              new Student(3, "Priscilla", "Art", 68),
              new Student(4, "Jacques", "Maths", 97),
              new Student(5, "Peter", "Science", 76));
    Map<Integer, String> studentMap = studentList.stream()
                          .collect(Collectors.toMap(Student::getRollNo, Student::getName));  
    System.out.println(studentMap);
  }
}
Output
{1=Mercy, 2=Ram, 3=Priscilla, 4=Jacques, 5=Peter}

If you want to collect to a Map where key is the student’s roll number and value is the student object then it can be done as. Here utility method Function.identity() is used which returns a function that always returns its input argument.

public class StreamToMap {

  public static void main(String[] args) {
    List<Student> studentList = Arrays.asList(new Student(1, "Mercy", "Science", 73),
              new Student(2, "Ram", "Science", 99),
              new Student(3, "Priscilla", "Art", 68),
              new Student(4, "Jacques", "Maths", 97),
              new Student(5, "Peter", "Science", 76));
    Map<Integer, Student> studentMap = studentList.stream()
                          .collect(Collectors.toMap(Student::getRollNo, Function.identity()));  
    System.out.println(studentMap);
  }
}
Output
{1=Roll Number: 1 Name: Mercy Marks: 73, 2=Roll Number: 2 Name: Ram Marks: 99, 3=Roll Number: 3 Name: Priscilla Marks: 68, 4=Roll Number: 4 Name: Jacques Marks: 97, 5=Roll Number: 5 Name: Peter Marks: 76}

2. Using Collectors.groupingBy() method

groupingBy() method also collects elements into a map by dividing elements into two lists of elements as per the passed grouping function. The collector produces a Map<K, List> where key specifies a group and List contains the elements which map to the associated key.

public class StreamToMap {

  public static void main(String[] args) {
    List<Student> studentList = Arrays.asList(new Student(1, "Peter", "Science", 75),
              new Student(2, "Ram", "Science", 99),
              new Student(3, "Priscilla", "Art", 68),
              new Student(4, "Mahesh", "Art", 62),
              new Student(5, "Scott", "Commerce", 72));
      Map<String, List<Student>> names = studentList.stream()
          .collect(Collectors.groupingBy(Student::getStream));
      // Iterating the returned Map
      names.entrySet().forEach(es->{System.out.println("Stream- " + es.getKey());
      System.out.println("**Students**");
      es.getValue().forEach(e->System.out.println(e.getName()));});
  }
}
Output
Stream- Art
**Students**
Priscilla
Mahesh
Stream- Science
**Students**
Peter
Ram
Stream- Commerce
**Students**
Scott

That's all for the topic Java Stream – Convert a Stream to Map. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment