Java Streams列表将出现索引映射为键

时间:2018-08-17 19:16:19

标签: java java-8 java-stream grouping

假设我有一个字符串列表

["bird", "bird", "dog", "dog", "bird","bog"]

我希望将它们收集为地图,形式为

{"bird": [0, 1, 4], "dog": [2, 3, 5]}

成为列表的值是单词在输入列表中的索引。

是否可以使用Java Streams做到这一点?

2 个答案:

答案 0 :(得分:15)

是的,您可以将IntStreamCollectors.groupingBy一起使用:

List<String> list = List.of("bird", "bird", "dog", "dog", "bird", "bog");

IntStream.range(0, list.size())
         .boxed()
         .collect(Collectors.groupingBy(list::get));

输出:

{bird=[0, 1, 4], bog=[5], dog=[2, 3]}

答案 1 :(得分:0)

稍微扭转一下上述问题。

给出一个对象列表,创建一个映射,其中“键”为“ x”字段,值为“ x”字段具有相同值的对象列表

@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);

    }

}

输出:

{=[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)]}

谢谢@Jacob的上述回答。