有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    上课

    另外两个答案是正确的here

    <>但是如果你用这个人的全名,考虑写一个班。如果你在其他地方使用这样的全名,那么就更有理由创建一个类

    在Java16及更高版本中,您可以选择使用新的record特性来更简单地定义类。在主要目的是以透明和不变的方式传输数据的情况下使用记录。编译器隐式地创建构造函数getters,equals&hashCodetoString

    record FullName ( String firstName , String lastName ) {}
    

    所以你的Person类看起来像这样

    class Person{
        private FullName name;
        private BigDecimal gpa;
        private int age;
    }
    

    用法示例

    Person p = new Person ( 
        new FullName( "Alice" , "Alba" ) , 
        new BigDecimal( "3.67" ) , 
        23 
    ) ;
    

    你的地图应该是这样的

    Map< FullName , Person > map = … 
    

    顺便说一句,在实践中,使用人名作为标识符几乎总是一个糟糕的想法。这就是为什么给学生分配学生识别号,员工获得员工ID,护照获得官方护照号,等等。我在回答问题时忽略了这个问题,而是把注意力集中在其他问题上……但要提前得到警告

  2. # 2 楼答案

    你可能需要小心重复的钥匙。如果键是重复的,那么就会抛出一个IllegalStateException

    对于复制键,请尝试以下操作:

    // This THROWS an Exception. DO NOT DO IF DUPLICATE KEYS
    // Map<PersonKey, Person> mapThrowException = list.stream().collect(
    //      Collectors.toMap(p -> new PersonKey(p.first, p.last), p -> p));
    
    
    
    
    // if duplicate key exists for two persons, choose the first person
    Map<PersonKey, Person> properMap = 
            list.stream().collect(
                  Collectors.toMap(
                        p -> new PersonKey(p.first, p.last), 
                        p -> p,  (person1, person2) -> person1 ));
    

    或者你可以使用Function.identity()来代替这个目的

    Map<PersonKey, Person> properMap2 = 
             list.stream().collect(
                    Collectors.toMap(
                          p -> new PersonKey(p.getFirst(), p.getLast()), 
                          Function.identity(),  
                          (person1, person2) -> person1 ));
        
    

    如果要求按键分组,并且不删除任何值(在重复键的情况下),请使用groupingBy(如@WJS所建议的):

    Map<PersonKey, List<Person>> properMapWithListForDuplicateKeys =
              list.stream().collect(
                      Collectors.groupingBy(
                            p -> new PersonKey(p.getFirst(), p.getLast())));
    
  3. # 3 楼答案

    我相信这就是你想要的(假设没有两个人同名)。密钥是使用Person的getter和PersonKey的构造函数动态构造的

    Map<PersonKey, Person> map = list.stream()
           .collect(Collectors.toMap(
                     person->new PersonKey(person.getFirst(),person.getLast()), 
                     person->person));
    
    

    为了容纳同名的人,你可以把他们放在Map<PersonKey,List<Person>>

    Map<PersonKey, List<Person>> map = list.stream()
                  .collect(Collectors.groupingBy(person->new 
                                  PersonKey(person.getFirst(),
                                            person.getLast())));