2015-06-17 178 views
4

嗨,我想從列表中檢索學生的名字,我使用過濾方法,但它返回boolean,所以有沒有其他方法可以這樣做?從列表中返回特定元素

public class Main { 

    public static void main(String[] args) { 
     Collection<Student> students=new LinkedList<>(); 
     students.add(new Student("Add","Nitkons",01)); 
     students.add(new Student("Nina","Adinson",02)); 
     students.add(new Student("Mick","McDonald",05)); 
     students.add(new Student("Anna","Lavrova",04)); 


     //doesnt work 
     Stream<Student> x=students.stream().filter(s->{return s.getName()}); 

    } 
} 

回答

9

您需要映射:

Stream<String> names = students.stream().map(Student::getName); 

,並收集了名的列表:

List<String> names = students.stream().map(Student::getName).collect(Collectors.toList());