How to achieve the output using java lambda function rather than iterating through for loop in?

Viewed 34

Here is my code. I'd like to achieve the output without using for loop. Tried different ways in Java with help of lambda expression but it didn't work. Any help/suggestions would be very helpful. Thank you!


public class Hobbies {
    
    private final HashMap<String, String[]> hobbies = new HashMap<String, String[]>();
    
    public void add(String hobbyist, String... hobbies) {
        this.hobbies.put(hobbyist, hobbies);
    }
    
    public List<String> findAllHobbyists(String hobby) {
        
        List<String> hobbyyist = new ArrayList<String>();
         
        for (Entry<String, String[]> entry : hobbies.entrySet()) {
            String name = entry.getKey();
            String[] list = entry.getValue();
            
            for(String s: list) {
                if(s.equalsIgnoreCase(hobby))
                    hobbyyist.add(name);
            }
        }  
        
        
        return hobbyyist;
    }
    
    public static void main(String[] args) {
        Hobbies hobbies = new Hobbies();
        hobbies.add("Steve", "Fashion", "Piano", "Reading");
        hobbies.add("Patty", "Drama", "Magic", "Pets");
        hobbies.add("Chad", "Puzzles", "Pets", "Yoga");

        System.out.println(Arrays.toString(hobbies.findAllHobbyists("Yoga").toArray()));
        
        
    }
}

1 Answers

Try this:

public List<String> findAllHobbyists(String hobby) {
        return hobbies.entrySet().stream()
                .filter(nameToHobbies -> Arrays.stream(nameToHobbies.getValue()).anyMatch(aHobby -> aHobby.equalsIgnoreCase(hobby)))
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
}

Also I'll suggest to rename hobbies map to namesToHobbies.

Also you can omit converting a list to an array in main:

public String[] findAllHobbyists(String hobby) {
        return hobbies.entrySet().stream()
                .filter(nameToHobbies -> Arrays.stream(nameToHobbies.getValue()).anyMatch(aHobby -> aHobby.equalsIgnoreCase(hobby)))
                .map(Map.Entry::getKey)
                .toArray(String[]::new)
}
Related