猿问

从 lambda 表达式 stream().filter() 返回字符串

我有这样的事情,我想得到一个字符串作为结果


    List<Profile> profile;

    String result = profile

                       .stream()

                       .filter(pro -> pro.getLastName().equals("test"))

                       .flatMap(pro -> pro.getCategory())

getCategory() 应该返回一个字符串,但不确定我必须使用什么来返回一个字符串,我尝试了几件事,但任何工作


任何的想法?


长风秋雁
浏览 1299回答 3
3回答

BIG阳

List<Profile>&nbsp;profile;String&nbsp;result&nbsp;=&nbsp;profile.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(pro&nbsp;->&nbsp;pro.getLastName().equals("test")) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.map(pro&nbsp;->&nbsp;pro.getCategory()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.findFirst() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.orElse(null);

拉风的咖菲猫

根据您尝试执行的操作,有几种解决方案。如果您有一个要获取其类别的目标配置文件,则可以使用findFirst或findAny来获取所需的配置文件,然后从生成的Optional.Optional<String> result = profile.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(pro -> pro.getLastName().equals("test"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(Profile::getCategory)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .findFirst(); // returns an Optional请注意,findFirst返回一个Optional。它以一种您可以优雅地处理的方式处理您实际上没有任何符合您的标准的可能性。或者,如果您尝试连接姓氏为“test”的所有配置文件的类别,则可以使用 a.collect(Collectors.joining())来累积字符串。List<Profile> profile; // contains multiple profiles with last name of "test", potentiallyString result = profile.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter( pro -> pro.getLastName().equals("test"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(Profile::getCategory)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.joining(", ")); // results in a comma-separated list

扬帆大鱼

您可以在您的流方法上使用 collect(Collectors.joining()) ,它将收集您的流作为字符串。在幕后,它将使用 StringJoiner 类:https&nbsp;://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html收集器类 java 文档:https&nbsp;:&nbsp;//docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#joining--我想它会帮助你
随时随地看视频慕课网APP

相关分类

Java
我要回答