0

I am in need of help to create a hashmap.

public class Driver {
    
    private String id;
    private String name;
    private List<Student> students;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Student> getStudents() {
        return students;
    }
    public void setStudents(List<Student> students) {
        this.students = students;
    }
}

public class Student {
    
    private String id;
    private String name;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

There will be a List of Driver objects. Every Driver has List of Student objects. Could someone help me how to create this Map using streams: <Student.id, Driver.id>

Thanks!

1 Answer 1

2

You can use flatMap to build a Stream of all the (Student ID, Driver ID) pairs and then collect them into a Map:

List<Driver> drivers = new ArrayList<> ();
Map<String,String>
    studentDrivers   =
        drivers.stream ()
               .flatMap (drv -> drv.getStudents ()
                                   .stream ()
                                   .map (st -> new SimpleEntry<String,String> (st.getId (), drv.getId ())))
               .collect (Collectors.toMap (Map.Entry::getKey, 
                                           Map.Entry::getValue));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.