How to convert List to Map - Key of Map should be a combination of multiple keys

Viewed 67

How to convert List to Map - Key of Map should be a combination of multiple keys

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class Student {
    private long id;
    private String firstName;
    private String lastName;
    private String street;
    private String city;

    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
                Student.builder().id(1).firstName("John").lastName("Doe").build(),
                Student.builder().id(1).firstName("Jane").lastName("Doe").build(),
                Student.builder().id(1).firstName("Mike").lastName("Doe").build(),
                Student.builder().id(1).firstName("Jack").lastName("Doe").build()
        );

        LinkedHashMap<Long, String> collect = students.stream()
                .collect(Collectors.toMap(
                        Student::getId, Student::getFirstName, (x, y) -> x + ", " + y, LinkedHashMap::new));
        System.out.println(collect);

        // Answer I am expecting is Ex: {1johnDoe=[id=1,firstName=John, lastName=Doe]}
    }

}
2 Answers

You can do as follows

LinkedHashMap<String, Student> collect = students.stream()
.collect(
    Collectors.toMap(
    student->(String.join("", Long.toString(student.getId()),student.getFirstName(),student.getLastName())),
    student->student,
    (v1,v2)->v1,
    LinkedHashMap::new));
        
collect.forEach((k,v)->System.out.println(k+"="+v));

I think, you want key as String and value as Student into map

Using Java 17

I have implemented the below code using some of the latest java features apart from Java 8.

Records in java 14 : As of JDK 14, we can replace our data classes with records. Records are immutable classes that require only the type and name of fields. We do not need to create constructor, getters, setters, override toString() methods, override hashcode and equals methods.

List.of() in java 9: It is a static method that returns the immutable list of elements passed as arguments. Here in the below scenario, we will get the list of four student objects.

public class Test {
      public static void main(String[] args) {
    
        record Student(long id, String firstName, String lastName,String street, String city){}
    
        Student s1 = new Student(1,"F1","L1","S1","C1");
        Student s2 = new Student(2,"F2","L2","S2","C2");
        Student s3 = new Student(3,"F3","L3","S3","C3");
        Student s4 = new Student(4,"F4","L4","S4","C4");
    
        Map<String,Student> output =
            List.of(s1,s2,s3,s4).stream().collect(Collectors.toMap(x -> x.id() + x.firstName(),
                Function.identity(), (k, v) -> k, LinkedHashMap::new));
    
        System.out.println(output);
      }
    }

Output:

{1F1=Student[id=1, firstName=F1, lastName=L1, street=S1, city=C1], 2F2=Student[id=2, firstName=F2, lastName=L2, street=S2, city=C2], 3F3=Student[id=3, firstName=F3, lastName=L3, street=S3, city=C3], 4F4=Student[id=4, firstName=F4, lastName=L4, street=S4, city=C4]}
Related