有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

lambda表达式流()中的java返回字符串。过滤器()

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

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

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

有什么想法吗

谢谢


共 (3) 个答案

  1. # 1 楼答案

    有一些解决方案取决于你想做什么。如果您有一个想要获得类别的目标配置文件,可以使用^{}^{}来获得所需的配置文件,然后从结果^{中获得类别

    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
    
  2. # 3 楼答案

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