Search code examples
javacollectionsjava-stream

How to put to the Map<Integer, Category> all values of List<Category> with key being taken from Category object itself with getId() using Stream API?


I use a loop to iterate through the list of categories, and for each category object, get its id using the getId() method and use it as the key to put the category object into the map. Here is an example code snippet:

Map<Integer, Category> categoryMap = new HashMap<>();
List<Category> categoryList = // get the list of categories from somewhere

for (Category category : categoryList) {
    int categoryId = category.getId();
    categoryMap.put(categoryId, category);
}

This code creates a new HashMap called categoryMap, and then iterates through the categoryList using a for-each loop. For each Category object in the list, it gets the id using getId(), and then puts the Category object into the map using the id as the key.

After this loop completes, categoryMap will contain all of the categories from categoryList, with their ids as the keys.

But how to use the same with Stream API? And if I want to concat 2 Lists?


Solution

  • I used the Collectors.toMap() method to collect the elements from both lists into a single map, where the key is taken from the getId() method of each Category object. Here is an example code snippet:

    List<Category> categoryList1 = // get the first list of categories from somewhere
    List<Category> categoryList2 = // get the second list of categories from somewhere
    
    Map<Integer, Category> categoryMap = Stream.concat(categoryList1.stream(), categoryList2.stream())
        .collect(Collectors.toMap(Category::getId, Function.identity()));
    

    This code concatenates the two lists using Stream.concat(), and then uses Collectors.toMap() to collect the elements from both lists into a single map. The first argument to toMap() is a function that extracts the key from each Category object (in this case, Category::getId), and the second argument is a function that returns the corresponding Category object (in this case, Function.identity()).

    After this code executes, categoryMap will contain all of the categories from both lists, with their ids as the keys. If there are any duplicate ids, an exception will be thrown. To handle duplicates, you can provide a merge function as a third argument to toMap().