Reputation: 451
Let's say I have a list of Strings
["bird", "bird", "dog", "dog", "bird","bog"]
And I want them to be collected as a Map in the form of
{"bird": [0, 1, 4], "dog": [2, 3, 5]}
being the lists values the indexes where the word is on the input list.
Is there a way to do this with Java Streams?
Upvotes: 3
Views: 518
Reputation: 1300
One Little twist to above problem.
Given a list of Objects, create a map where Key is 'x' field and value is list of Objects with same value for 'x' field
@Value
@RequiredArgsConstructor
class Employee{
String Firstname;
String LastName;
String Dept;
Integer Salary;
}
public class EmployeeStreamTest {
public static void main(String[] args) {
Employee e1 = new Employee("ABC", "Raval", "Fin", 100);
Employee e2 = new Employee("BCD", "Raval", "Fin", 100);
Employee e3 = new Employee("CDE", "Raval", "Fin", 100);
Employee e4 = new Employee("WXY", "", "Fin", 100);
Employee e5 = new Employee("XYZ", "", "Fin", 100);
Stream<Employee> es = Stream.of(e1,e2,e3,e4,e5);
//given a list of employees , create a map where Key is last name and value is list of employees with same last name
Map<String, List<Employee>> lmse = es.collect(Collectors.groupingBy(emp -> emp.getLastName()));
System.out.println(lmse);
}
}
Output:
{=[Employee(Firstname=WXY, LastName=, Dept=Fin, Salary=100), Employee(Firstname=XYZ, LastName=, Dept=Fin, Salary=100)], Raval=[Employee(Firstname=ABC, LastName=Raval, Dept=Fin, Salary=100), Employee(Firstname=BCD, LastName=Raval, Dept=Fin, Salary=100), Employee(Firstname=CDE, LastName=Raval, Dept=Fin, Salary=100)]}
Thank you @Jacob for above answer.
Upvotes: 0
Reputation: 29680
Yes, you can use an IntStream
along with Collectors.groupingBy
:
List<String> list = List.of("bird", "bird", "dog", "dog", "bird", "bog");
IntStream.range(0, list.size())
.boxed()
.collect(Collectors.groupingBy(list::get));
Output:
{bird=[0, 1, 4], bog=[5], dog=[2, 3]}
Upvotes: 16