0

How to convert list to Map<Integer, Map<Integer, List<Person>>> use java lambda?

I only know this:

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

I only know this:

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

But I don't know how to write use Map to be a key in Map. 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)));
kingdelee
  • 15
  • 4

1 Answers1

1
Map<Integer, Map<Integer, List<Person>>> collect = personList.stream().collect(Collectors
                .groupingBy(Person::getAge, Collectors.groupingBy(Person::getCityCode)));
Master Chief
  • 2,520
  • 19
  • 28
  • Hello, Master, I found the other problem, I update my question, please help me . If the group2 want to use group1 result, how to do ? – kingdelee May 08 '19 at 11:29
  • Hi @kingdelee, Can you create it as a new question. The question you asked earlier is in itself a whole question which could be helpful to someone else too. Also you have already marked this answer as correct answer. I will definitely have a look into your other (new) problem. – Master Chief May 08 '19 at 11:33
  • Ok, I know it. I create a new question in https://stackoverflow.com/questions/56040098/how-to-use-group-1-result-key1-in-group-2-when-use-java-lambda-like-mapkey1-ma. Please and thank you. ^_^ – kingdelee May 08 '19 at 11:48