'Hashmap - cannot infer arguments

Hey :) This is my first post and my first approach at streams! I am trying to learn it by myself, but since its a new style of programming Im having a tough time :D

So here's my problem:

In the following Method I have a Map of <Long, Ingredient> as parameter. (Ingredient has the String Attribute "name".)

I want to return an inverted Map of <String, Long>. (The string being the Attribute "name" of the class Ingredient.)

Here is my solution using a for-loop (which worked)

public static Map<String, Long> focusOnNameAndInvert(Map<Long, Ingredient> articles) {
    ArrayList<String> nameList = new ArrayList<>(articles.values().stream().map(Ingredient::getName).collect(Collectors.toList()));
    ArrayList<Long> keyList = new ArrayList<>(articles.keySet());

    Map<String, Long> nameAndInvertedMap = new HashMap<>();
    for (int i = 0; i<nameList.size(); i++){
        nameAndInvertedMap.put(nameList.get(i), keyList.get(i));
    }

    return nameAndInvertedMap;
}

Here is my approach on using streams (which I need help with)

The "<>" on the right side of initializing the HashMap is red underlined and says "Cannot infer arguments" (Using IntelliJ)

public static Map<String, Long> focusOnNameAndInvert(Map<Long, Ingredient> articles) {
    Map<String, Long> nameAndInvertedMap =  new HashMap<>(
            articles.values().stream().map(Ingredient::getName),
            articles.keySet().stream().map(articles::get));


    return nameAndInvertedMap;
}

Thank you for all input, tips, critique and especially for your time! Wishing you all a nice day :-)



Solution 1:[1]

Your stream is incorrect. Should be something like this:

public static Map<String, Long> focusOnNameAndInvert(Map<Long, Ingredient> articles) {
  return articles.entrySet().stream()
      .collect(Collectors.toMap(entry -> entry.getValue().getName(), Map.Entry::getKey));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tbjorch