如何用Java 8 Stream改写含内部for循环的电影匹配方法?
改写方案
当然可以,我们可以利用Java 8 Stream的allMatch方法替代内部for循环,同时简化Optional的处理逻辑,改写后的代码如下:
public Optional<String> getIdFromMatchedMovie(List<Movie> movies, Map<String, Object> attributes) { return movies.stream() .filter(movie -> attributes.entrySet().stream() .allMatch(entry -> { Object movieAttrValue = movie.getAttributes().get(entry.getKey()); return movieAttrValue != null && movieAttrValue.equals(entry.getValue()); })) .findFirst() .map(Movie::getId); }
关键改动说明
- 替换内部for循环:原逻辑中遍历属性条目逐一匹配的for循环,被
attributes.entrySet().stream().allMatch(...)替代。allMatch方法会验证所有属性条目都满足匹配条件,和原逻辑的“所有属性必须完全匹配”要求完全一致。 - 简化Optional处理:原方法中手动判断
isPresent()再提取ID的逻辑,改用map(Movie::getId)直接将Optional<Movie>转换为Optional<String>,当没有匹配电影时自动返回Optional.empty(),代码更简洁流畅。
内容的提问来源于stack exchange,提问作者Yamazaki
相关产品推荐
相关产品推荐

