-1

Using Java stream API Need to convert List of custom object to

Map<String, Map<String,String>>

Map<String,List<CustomClass>> map =list.stream().collect(Collectors.groupingBy(i -> i.somevariable1(),Collectors.mapping(i->new CustomClass(i.somevariable(),i.somevariable2()),
Collectors.toList())));

Here List is changed to Map<String,String> so expected return format needs to be changed to Map<String, Map<String,String>>

Harry
  • 5
  • 1
  • 6
  • 1
    I think this link can help you: https://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v – Ali Aug 03 '22 at 09:00
  • 2
    Please [*edit*](https://stackoverflow.com/posts/73218917/edit) the question and share a simplified structure of `CustomClass`. Also clarify is values of `somevariable1` are unique, and how does the `equals/hashCode` contract implemented in your `CustomClass`? If a duplicate would be encountered while generating this nested map, what are the policies? – Alexander Ivanchenko Aug 03 '22 at 09:41

1 Answers1

1

Suppose you have a class as

class MyObject {
    private String var1;
    private String var2;
    private String var3;

    MyObject(String var1, String var2, String var3) {
        this.var1 = var1;
        this.var2 = var2;
        this.var3 = var3;
    }

    public String getVar1() {
        return var1;
    }

    public String getVar2() {
        return var2;
    }

    public String getVar3() {
        return var3;
    }
}

and you have one list myObjects which is containing objects of class MyObject. To convert this list to a map

Map<String, Map<String, String>> map = myObjects.stream().collect(Collectors.toMap(MyObject::getVar1, o -> Map.of(o.getVar2(), o.getVar3())));