Ronald
Ronald

Reputation: 2917

Map.merge .. non-static method cannot be referenced from static context

I have the following code:

    public List<String> myMethod(){
    ..
    ...... 
    Map<String, Module> m1 = new HashMap<>();
    Map<String, Module> m2= new HashMap<>();
    Set<Map.Entry<String, Module>> entries = m2.entrySet();
    for( Map.Entry<String, Module>  e : entries){
        m1.merge(e.getKey(),e.getValue(),String::concat);
        }
    .....
   }

I get error line here String::concat with the message non-static method cannot be referenced from static context

any idea how to solve this issue?

Upvotes: 1

Views: 2425

Answers (2)

Anton Hlinisty
Anton Hlinisty

Reputation: 1467

Your map value is of type Module. String::concat returns a String, your third argument needs to return you a "merged" Module instead of String::concat.

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56469

Map::merge takes a BiFunction as its last argument to merge the values where there is a key collision.

You'll need to find a way to merge two given Module's not String.

in other words, it's:

 m1.merge(e.getKey(),e.getValue(),(Module l, Module r) -> ...);

On another note, you can simplify your code to:

m2.forEach((k, v) -> m1.merge(k, v, (Module l, Module r) -> ...));

Upvotes: 1

Related Questions