-1
public class Cont {
    public String getContinent() {
        return continent;
    }

    public void setContinent(String continent) {
        this.continent = continent;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public Cont(String continent, String country) {
        super();
        this.continent = continent;
        this.country = country;
    }

    String continent;
    String country;
}

In Main::


        ArrayList<Cont> cList = new ArrayList<Cont>();
        cList.add(new Cont("Asia", "China"));
        cList.add(new Cont("Asia", "India"));
        cList.add(new Cont("Europe", "Germany"));
        cList.add(new Cont("Europe", "France"));
        cList.add(new Cont("Africa", "Ghana"));
        cList.add(new Cont("Africa", "Egypt"));
        cList.add(new Cont("South America", "Chile"));

Using java streams, How can i get a Map<String,List> with following values

{South America=[Chile], Asia=[China, India], Europe=[Germany, France], Africa=[Ghana, Egypt]}

  • Check out Collectors.toMap(). https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap-java.util.function.Function-java.util.function.Function-java.util.function.BinaryOperator- – Marcus Dunn Nov 06 '22 at 03:37

1 Answers1

0

You can do this

         var map = cList.stream()
            .collect(
                    Collectors.toMap(
                            p -> p.getContinent(),
                            p -> List.of(p.getCountry()),
                            (v1, v2) -> { 
                                // merge collusion function
                                var list = new ArrayList<String>();
                                list.addAll(v1);
                                list.addAll(v2);
                                return list;
                            }));
System.out.println("map" + map.toString());
N_A_P
  • 41
  • 3