我有一个School
具有名称 String
的类字段。
public class School {
private final String name;
public School(String name) {
this.name = name;
}
// getter and setter ...
}
我得到了一个ArrayList
的School
实例:
List<School> shoolList = // Got value of ArrayList<School>
我想要一个Set<String>
其中包含上面所有学校名称 List
。我尝试使用 map()
流API:
schooList.stream().map(school -> school.getName())
但是有没有一种简单的方法可以获得 Set<String>
从上面的结果中输入结果?
最佳答案
使用收集器
:
Set<String> allNames = schoolList.stream()
.map(School::getName)
.collect(Collectors.toSet());
有关详细信息,请参阅:https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
关于java - 从 ArrayList<MyObject> 获取 Set<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58082067/