Как скрыть список на карту <T, <K, список <Person>>> использовать Java лямбда? - PullRequest
0 голосов
/ 08 мая 2019

Как преобразовать список в Map<Integer, Map<Integer, List<Person>>> использовать Java-лямбду?

Я знаю только это:

private static Map<Dish.Type, List<String>> groupDishNamesByType() {
        return menu.stream().collect(groupingBy(Dish::getType, mapping(Dish::getName, toList())));
    }

Я знаю только это:

 public static <T, F> Map<F, T> listToMap(List<T> list, Function<T, F> f) {
        return list.stream().collect(Collectors.toMap(f, obj -> obj));
    } 

Но я не знаю, как писать, используйте карту, чтобы быть ключом к карте. Pherhaps:

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

method:

// Map<age, Map<cityCode, List<Person>>>
public Map<Integer, Map<Integer, List<Person>>> covertListToMap(List<Person> list){

      // TODO: How to make List<Person> to Map<age, Map<cityCode, List<Person>>>

}


Thank you floor-1 @Master chief.
But now I found the other problem:
When the build first group's key , get a key1result, I want to use it in second group, How to do it? -_-


 Function<Person, Integer> key1 = (Person p) -> {
            // do many sth then get a key1Result:
            int key1Result = p.getAge() * new Random(10).nextInt();
            return key1Result;
        };

        Function<Person, Integer> key2 = (Person p) -> {
            //  Question: how to get and use Function key1 key1Result:

            int key1Result = 0;

            int result = p.getCityCode() + key1Result;
            return result;
        };

        Map<Integer, Map<Integer, List<Person>>> collect = list.stream().collect(groupingBy(key1, groupingBy(key2)));

1 Ответ

1 голос
/ 08 мая 2019
Map<Integer, Map<Integer, List<Person>>> collect = personList.stream().collect(Collectors
                .groupingBy(Person::getAge, Collectors.groupingBy(Person::getCityCode)));
...