David Ling
David Ling

Reputation: 145

How to return the values of a filtered Hashmap in java?

So ive created this HashMap and have gone ahead filtered it using lambda and 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));
    }

}

How can I improve my last line of code so that it returns the filtered Value? Right now it returns : Another named Engine=javaapplication40.CarEngine@6ce253f1

I also attempted this way

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);

Upvotes: 1

Views: 87

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

It seems you are searching for :

CarEngine find = hmap.values().stream()
                   .filter(e -> e.getEngineName().contains(a)) 
                   .findFirst() 
                   .orElse(null);

Upvotes: 1

Related Questions