java - Convert List<Object> in Map<attributeA,List<attributeB> -
public class test { public void foo() { arraylist<person> persons = new arraylist<>(); persons.add(new person("marco", "bianchi")); persons.add(new person("marco", "rossi")); persons.add(new person("marco", "verdi")); persons.add(new person("giacomo", "bianchi")); persons.add(new person("giacomo", "rossi")); persons.add(new person("giacomo", "verdi")); map<string, list<string>> map = ?? } class person { string name; string surname; public string getname() { return name; } public string getsurname() { return surname; }
i need have map<name, list<surname>>
when name
equal , surname
in list. expected result:
{ marco=[bianchi, rossi, verdi], giacomo=[bianchi, rossi, verdi] }
can me?
i need lambda function solution.
if using java 8 take @ stream api. here example how easy solve task:
public class mapexample { public static void main(string[] args) { arraylist<person> people = new arraylist<>(); people.add(new person("marco", "bianchi")); people.add(new person("marco", "rossi")); people.add(new person("marco", "verdi")); people.add(new person("giacomo", "bianchi")); people.add(new person("giacomo", "rossi")); people.add(new person("giacomo", "verdi")); map<string, list<string>> map = people.stream() .collect( collectors.groupingby(person::getname, collectors.mapping(person::getsurname, collectors.tolist())) ); } }
with static import looks more declarative:
import static java.util.stream.collectors.*; // .... map<string, list<string>> map = people.stream() .collect( groupingby(person::getname, mapping(person::getsurname, tolist())) );
Comments
Post a Comment