android java Map merge with custom BiFunction

Larry Tseng :

Using Java on Android, I want to merge an element into a Map with a custom remapping function.

Map<String, MyObject> map = new HashMap<String, MyObject>();
// init map with some values here....  then
MyObject xMyObject = new MyObject(123); // init this instance of MyObject
map.merge("key", xMyObject, myRemappingFunction);

I understand Android Java does not have Java 8 support for lambda expressions. So I think I need to implement myRemappingFunction as a BiFunction, but I'm having trouble with understanding the BiFunction interface declaration to get anything to compile.

public static BiFunction<? super MyObject,? super MyObject,? extends MyObject> remappingfunction()

Any hints please?

Naman :

The remappingFunction is an implementation of BiFunction<? super MyObject, ? super MyObject,? extends MyObject> which is evaluated using the apply method that you need to define here.

Consider an example when you would merge the integer attribute val (by summing) of your MyObject if they are mapped to the same key, the implementation would look like :

map.merge("key", xMyObject, new BiFunction<MyObject, MyObject, MyObject>() {
    // this is the definition of what to do for two such values
    @Override
    public MyObject apply(MyObject myObject1, MyObject myObject2) {
        return new MyObject(myObject1.getVal() + myObject2.getVal());
    }
});

this could also be represented in lambda as :

map.merge("key", xMyObject, 
                (myObject1, myObject2) -> new MyObject(myObject1.getVal() + myObject2.getVal()));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=160581&siteId=1