【问题标题】:How can I make a Collection of Integer using a List of "Person"?如何使用“人员”列表制作整数集合?
【发布时间】:2013-12-12 15:24:28
【问题描述】:

您好,我是新来的,我有一个问题。

我有这个对象。

    public Person(int id,String name, int age){ 
    this.id=id;
    this.name=name;
    this.age=age;   
    }

我想创建一个学生 ID 集合。

到现在为止

    List<Person> students=new ArrayList<Person>(); 

    Collection<Integer> studentsIds=new ArrayList<Person>(students);

有人可以帮我吗?

【问题讨论】:

  • 为什么需要两组数据? Person 类包含所有 id。如果您需要一个 id 列表,只需遍历学生列表
  • 您可能想查看 HashMap,它是 KeyValues 的集合。根据您使用此代码的目标,它可能更接近您想要实现的目标。

标签: java list object collections


【解决方案1】:

你不能那样做。两者都是不同的数据类型。所以创建一个 Integer 集合,然后查看 people 集合。

List<Integer> studentsIds=new ArrayList<Integer>();

然后

for (Person p : students){

  studentsIds.add(p.age); // change to p.id if you need

}

【讨论】:

    【解决方案2】:

    你必须做这样的事情

    for(Person s: students) studentIds.add(s.id);
    

    【讨论】:

      【解决方案3】:

      虽然其他人给出了正确答案,但您也可以在 Java 8 中使用 lambda 表达式来实现:

      List<Integer> studentsIds = students.stream()
                                          .map(student -> student.id)
                                          .collect(Collectors.toList());
      

      【讨论】:

        【解决方案4】:

        如果没有 Java 8 lambda,您可以在 Guava 库的帮助下使用匿名类:

        List<Integer> studentsIds = Lists.transform(students, getStudentId);
        
        private final Function<Person, Integer> getStudentId =
                new Function<Person, Integer>() {
                    @Nullable
                    @Override
                    public Integer apply(@Nullable Person student) {
                        return student == null ? null : student.id;
                    }
                };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多