Java 从lambda表达式流()返回字符串。筛选器()
我有这样的东西,我想得到一个字符串作为结果Java 从lambda表达式流()返回字符串。筛选器(),java,lambda,Java,Lambda,我有这样的东西,我想得到一个字符串作为结果 List<Profile> profile; String result = profile .stream() .filter(pro -> pro.getLastName().equals("test")) .flatMap(pro -> pro.getCategory()
List<Profile> profile;
String result = profile
.stream()
.filter(pro -> pro.getLastName().equals("test"))
.flatMap(pro -> pro.getCategory())
列表配置文件;
字符串结果=配置文件
.stream()
.filter(pro->pro.getLastName().equals(“测试”))
.flatMap(pro->pro.getCategory())
getCategory()应该返回一个字符串,但不确定我必须使用什么来返回字符串,我尝试了几种方法,但都成功了
有什么想法吗
感谢列表配置文件;
字符串结果=profile.stream()
.filter(pro->pro.getLastName().equals(“测试”))
.map(pro->pro.getCategory())
.findFirst()
.orElse(空);
列表配置文件;
字符串结果=profile.stream()
.filter(pro->pro.getLastName().equals(“测试”))
.map(pro->pro.getCategory())
.findFirst()
.orElse(空);
根据您要做的事情,有几种解决方案。如果您有一个要获取类别的目标配置文件,您可以使用或获取所需的配置文件,然后从生成的可选中获取类别
Optional<String> result = profile.stream()
.filter(pro -> pro.getLastName().equals("test"))
.map(Profile::getCategory)
.findFirst(); // returns an Optional
有一些解决方案取决于您试图做什么。如果您有一个要获取类别的目标配置文件,您可以使用或获取所需的配置文件,然后从生成的可选中获取类别
Optional<String> result = profile.stream()
.filter(pro -> pro.getLastName().equals("test"))
.map(Profile::getCategory)
.findFirst(); // returns an Optional
您可以在流方法collect(Collectors.joining())上使用,该方法将以字符串形式收集流。
在引擎盖下,它将使用StringJoiner等级:
收集器类java文档:
我认为它将帮助您您可以在流方法collect(Collectors.joining())上使用它,该方法将流收集为字符串。
在引擎盖下,它将使用StringJoiner等级:
收集器类java文档:
我认为它会帮助您如果流中有多个元素怎么办?为什么要调用flatMap()
?是的,实际上是在.filter()之后使用findFirst().collector(collector.joining())代码>?你真的只是想得到姓氏为“test”的配置文件的类别吗?或者您正在尝试将姓氏为“test”的所有配置文件的所有类别收集到一个字符串中?如果流中有多个元素怎么办?为什么要调用flatMap()
?是的,实际上是在.filter()之后使用findFirst()。collect(collector.joining())代码>?你真的只是想得到姓氏为“test”的配置文件的类别吗?或者你想把所有姓氏为“test”的配置文件的所有类别都收集到一个字符串中吗?谢谢,我用Optional尝试了第一个,效果很好,谢谢,谢谢,谢谢,谢谢,我用Optional尝试了第一个,效果很好,非常感谢
List<Profile> profile; // contains multiple profiles with last name of "test", potentially
String result = profile.stream()
.filter( pro -> pro.getLastName().equals("test"))
.map(Profile::getCategory)
.collect(Collectors.joining(", ")); // results in a comma-separated list