2013-12-12 25 views
2

嗨,我是新來的,我有一個問題。如何使用「人物」列表製作整數集合?

我有這個對象。

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

而我想創建一個Collection studentsIds。

到現在爲止我已經

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

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

有人能幫助我嗎?

+1

爲什麼要使用兩組數據? Person類包含所有的id。如果你需要一個ID列表,只需遍歷學生列表 –

+0

你可能想查看一個[HashMap](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap .html)這是一個KeyValues的集合。這可能更接近你想要實現的目標,取決於你使用這段代碼的目標。 – DoubleDouble

回答

5

你不能這樣做。兩者都是不同的數據類型。因此,創建一個Integer集合,然後查看個人集合。

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

然後

for (Person p : students){ 

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

} 
1

你將不得不做這樣的事情

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

當別人指出一個正確的答案,你也可以用Java 8中使用lambda表達式實現這一目標:

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

沒有Java 8您可以在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; 
      } 
     };