【问题标题】:How to group objects by two fields in an inner class如何按内部类中的两个字段对对象进行分组
【发布时间】:2020-05-22 18:05:10
【问题描述】:

请帮我按两个字段将对象与内部对象分组。

我有List<Man> 并且需要将它们按两个内置地址对象字段分组? 我想在答案中实现以下结构 Map<String, Map<String, List<Man>>> 其中第一个字符串是城市,第二个字符串是街道

public class Man {
  private String name;
  private Address address;

  public Man(String name, Address address) {
        this.name = name;
        this.address = address;
    }
}

public class Address {
  private String city;
  private String street;

  public Address(String city, String street) {
        this.city = city;
        this.street = street;
    }
}


public static void main(String[] args) {
        List<Man> mans = new ArrayList<>();
        mans.add(new Man("Jonh", new Address("NY", "123 street")));
        mans.add(new Man("Alex", new Address("Denver", "6 street")));
        mans.add(new Man("Kate", new Address("NY", "123 street")));
        mans.add(new Man("Mary", new Address("Denver", "12 street")));

  //How can I get the following answer? 
  //Map<String, Map<String, List<Man>>>,  where first string is a city, and second string is street 

  // NY -
  //     |
  //     "123 street" - 
  //                  |
  //                   Man(Jonh...)
  //                   Man(Kate...)
  // Denver -
  //         |
  //         "6 street" -
  //                    |
  //                    Man(Alex...)
  //         |
  //          "12 street" -
  //                       |
  //                       Man(Mary...)

}

【问题讨论】:

    标签: java dictionary collections java-8 java-stream


    【解决方案1】:

    您可以将涉及 lambda 的嵌套分组用于此类任务:

    Map<String, Map<String, List<Man>>> output = mans.stream()
            .collect(Collectors.groupingBy(m ->m.getAddress().getCity(), 
                    Collectors.groupingBy(m -> m.getAddress().getStreet())));
    

    【讨论】:

    • 非常感谢,我会将答案标记为解决方案。
    【解决方案2】:

    你可以使用嵌套的Collectors.groupingBy:

    mans.stream()
        .collect(Collectors.groupingBy(
            m -> m.getAddress().getCity(), 
            Collectors.groupingBy(m -> m.getAddress().getStreet())))
    

    结果是:

    {
        Denver={
            6 street=[Man@7791a895], 
            12 street=[Man@3a5ed7a6]
    }, 
        NY={
            123 street=[Man@6325a3ee, Man@1d16f93d]
        }
    }
    

    【讨论】:

    • toString for Man 将有助于进一步澄清:)
    【解决方案3】:
    Map<String, Map<String, List<Man>>> output = mans.stream()
        .collect(Collectors.groupingBy(man ->man.getAddress().getCity(), 
                Collectors.groupingBy(m -> m.getAddress().getStreet())));
    

    【讨论】:

    • 嗨,欢迎来到堆栈溢出。请编辑您的答案并添加其作用或工作方式的描述。没有解释的答案可能会被删除,因为不熟悉情况的人可能不知道他们的重点是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 2012-08-22
    • 2011-10-18
    相关资源
    最近更新 更多