3 回答

TA贡献1859条经验 获得超6个赞
List<Profile> profile;String result = profile.stream() .filter(pro -> pro.getLastName().equals("test")) .map(pro -> pro.getCategory()) .findFirst() .orElse(null);

TA贡献1995条经验 获得超2个赞
根据您尝试执行的操作,有几种解决方案。如果您有一个要获取其类别的目标配置文件,则可以使用findFirst或findAny来获取所需的配置文件,然后从生成的Optional.
Optional<String> result = profile.stream()
.filter(pro -> pro.getLastName().equals("test"))
.map(Profile::getCategory)
.findFirst(); // returns an Optional
请注意,findFirst返回一个Optional。它以一种您可以优雅地处理的方式处理您实际上没有任何符合您的标准的可能性。
或者,如果您尝试连接姓氏为“test”的所有配置文件的类别,则可以使用 a.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

TA贡献1799条经验 获得超9个赞
您可以在您的流方法上使用 collect(Collectors.joining()) ,它将收集您的流作为字符串。在幕后,它将使用 StringJoiner 类:https ://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html
收集器类 java 文档:https : //docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#joining--
我想它会帮助你
添加回答
举报