因此,我创建了此Hashmap,并使用lambda和Stream对其进行了过滤
public class engineMain {
public static void main(String[] args) {
CarEngine engineOne = new CarEngine("A named Engine", 2000, 8, "E10");
CarEngine engineTwo = new CarEngine("Another named Engine", 2200, 6, "E10");
String a = "Another named Engine";
HashMap<String, CarEngine> hmap = new HashMap();
hmap.put(engineOne.getEngineName(), engineOne);
hmap.put(engineTwo.getEngineName(), engineTwo);
hmap.entrySet().stream().filter(e -> e.getValue().getEngineName().contains(a)).forEach(e -> System.out.println(e));
}
}
如何改善我的最后一行代码,使其返回过滤后的值?现在它返回Another named Engine=javaapplication40.CarEngine@6ce253f1
我也尝试过这种方式
HashMap<String, CarEngine> map = new HashMap<>();
map.entrySet().stream().filter(x -> x.getKey().equals(a)).flatMap(x -> ((Map<String,CarEngine>) x.get(a)).values().stream()
.forEach(System.out::println);
谢谢
似乎您正在搜索:
CarEngine find = hmap.entrySet().stream()
.filter(e -> e.getValue().getEngineName().contains(a))
.map(Map.Entry::getValue)
.findFirst()
.orElse(null);