Diyyu
Diyyu

Reputation: 35

convert List<E> to Map<String, List<String>> using java 8 streams

I am looking for some help in converting a List of objects to a Map<String, List<String>>.

class Person {   
    private String name;    
    private int age;
}

I have a List<Person> and I want to collect Map<int, List<String>> with key being age and value being list of names of Persons with same age.

I tried in these lines but did not work

persons.stream().collect(Collectors.groupingBy(p -> p.getAge()), );

Upvotes: 2

Views: 584

Answers (2)

Syed Belal Jafri
Syed Belal Jafri

Reputation: 141

If the purpose of this is to enable fast lookup, have you thought about using an indexed collection like Data Store:

https://github.com/jparams/data-store

You can do something like :

Store<Person> store = new MemoryStore<Person>();
store.index("name", Person::getName);
store.addAll(listOfPeople); // populate your store with data
Person personFound = person.get("name", "bob");

You can multiple indexes on the same data. You can even create case insensitive indexes etc.

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56423

Use this overload of groupingBy which accepts a downstream collector:

Map<Integer, List<String>> map = persons.stream()
        .collect(Collectors.groupingBy(Person::getAge,
                Collectors.mapping(Person::getName, Collectors.toList())));

Upvotes: 6

Related Questions