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

3

我有类似这样的东西,希望能得到一个字符串作为结果。

    List<Profile> profile;
    String result = profile
                       .stream()
                       .filter(pro -> pro.getLastName().equals("test"))
                       .flatMap(pro -> pro.getCategory())

getCategory() 应该返回一个字符串,但我不确定该使用什么来返回一个字符串,我尝试了几种方法但是都没有成功

有什么想法吗?

谢谢


2
如果流中有多个元素怎么办? - rgettman
2
你为什么要调用 flatMap() ? - shmosel
是的,实际上在.filter()之后我使用了findFirst()。 - William
.collect(Collectors.joining());... ? - Roddy of the Frozen Peas
如果只有一个姓为“test”的人,请使用 findFirst - VHS
显示剩余2条评论
3个回答

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

3

根据您的需求,有几种解决方案。如果您只针对一个特定的配置文件进行分类,可以使用findFirstfindAny来获取所需的配置文件,然后从结果的Optional中获取分类。

Optional<String> result = profile.stream()
                                .filter(pro -> pro.getLastName().equals("test"))
                                .map(Profile::getCategory)
                                .findFirst(); // returns an Optional

请注意,findFirst返回一个Optional。它处理了可能没有符合条件的元素的情况,以便您可以优雅地处理。
或者,如果您正在尝试连接所有姓为“test”的配置文件的类别,则可以使用.collect(Collectors.joining())来累积字符串。
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

谢谢,我尝试了第一个带有可选项的方法,它起作用了,非常感谢。 - William

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接