Ask Your Question
2

How can you arrange a Map consisting of a collection of CustomObjects, where each CustomObject has multiple variables, based on a specific variable in the CustomObject?

asked 2021-05-01 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-01-27 15:00:00 +0000

lalupa gravatar image

You can create a Map with the specific variable as the key and a list of CustomObjects as the value. Here's an example in Java:

Map<String, List<CustomObject>> customObjectMap = new HashMap<>();

// Assume each CustomObject has a String variable called "category"
for (CustomObject customObject : customObjectList) {
    String category = customObject.getCategory();

    if (!customObjectMap.containsKey(category)) {
        customObjectMap.put(category, new ArrayList<>());
    }

    customObjectMap.get(category).add(customObject);
}

In this example, we iterate through a list of CustomObjects and retrieve the value of their "category" variable. We check if the Map already contains that category as a key and if not, we add a new key-value pair to the Map with an empty list as the value. We then retrieve the list for that category and add the current CustomObject to it.

After this loop has completed, the customObjectMap will contain all the CustomObjects grouped by their category variable. You can then access the list of CustomObjects for each category by using the category variable as the key.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-01 11:00:00 +0000

Seen: 11 times

Last updated: Jan 27 '22