0

I have a map which has as key string, and as a value a list of objects Names. In this map, I saved information some years about a Names. Each object of the `` class has a name, gender and rank atributes.

Map <String, ArrayList<Names>> myMap = new TreeMap<>();

I tried to do this but it doesn't work:

List<Names> filterList = myMap.filter((k, v) -> v.name == name).collect(Collectors.toList);
0

2 Answers 2

1

Assuming that the input map is like this:

Map<String, List<BabyName>> inputMap;

The list of BabyName should be retrieved using flatMap and filter operations of Stream API:

List<BabyName> result = inputMap.values() // Collection<List<BabyName>>
        .stream() // Stream<List<BabyName>>
        .flatMap(List::stream) // Stream<BabyName>
        .filter(bn -> bn.getRank() == 3) // filtered Stream<BabyName>
        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

0

This is how I would have done it, not sure if I am being helpful here. I'm fairly new to Java and programming in general.

//Method that takes an ArrayList, filter the list, and returns a new ArrayList
public static ArrayList<BabyName> filterArrayList(ArrayList<BabyName> inputList, int filter) {
        ArrayList<BabyName> returnList = new ArrayList<>();
        for (BabyName babyName: inputList) {
            if (babyName.getRank() == filter)
                returnList.add(babyName);
        } return returnList;
    }

This block of code basically iterates the TreeMap, and calls the above method. The ArrayList returned by the above method gets added to a new ArrayList mFilteredList.

ArrayList<BabyName> mFilteredList = new ArrayList<>();

for (Iterator<ArrayList<BabyName>> iterator = myMap.values().iterator(); iterator.hasNext(); ) {
            ArrayList<BabyName> nameList = iterator.next();
            mFilteredList.addAll(filterArrayList(nameList, 2));
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.