I've got a class which contains the following:
List roles = ldapTemplate.search(baseDn, replaceFilter, sc, new AttributesMapper() { public Object mapFromAttributes(Attributes attrs) throws NamingException { return attrs.get("cn").get(); } });
IntelliJ tells me to replace the anonymous inner class with a lambda. So I tried:
List roles = ldapTemplate.search( baseDn, replaceFilter, sc, (Attributes a) -> { return a.get("cn").get(); }; );
However, I get a compilation error:
Error:(46, 50) java: incompatible types: inference variable T has incompatible bounds equality constraints: java.lang.String lower bounds: java.lang.Object
I can't find the solution to this problem. Do you have any ideas?
Since the most common use of Anonymous class is to provide a throwaway, stateless implementation of abstract class and interface with a single function, those can be replaced by lambda expressions, but when you have a state field or implementing more than one interface, you cannot use lambdas to replace the anonymous ...
Lambda expression can be used where a class implements a functional interface to reduce the complexity of the code. An inner anonymous class is more powerful as we can use many methods as we want, whereas lambda expression can only be used where an interface has only a single abstract method.
Lambda expressions are introduced in Java 8. These are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.
Can every anonymous class be replaced by a lambda expression? The answer is no.
Try this (removing extra semi colon)
List roles = ldapTemplate.search( baseDn, replaceFilter, sc, (Attributes a) -> { return a.get("cn").get(); } );
A simple azure storage Entity Resolver interface and it's implemented method:
EntityResolver<String> orderNumberResolver = new EntityResolver<String>() { @Override public String resolve(String partitionKey, String rowKey, Date timeStamp, HashMap<String, EntityProperty> properties, String etag) { return properties.get("SomeColumnName").getValueAsString(); } };
Lambda of the above method will be :
EntityResolver<String> orderNumberResolver = ( partitionKey, rowKey, timeStamp, properties, etag ) -> properties.get("SomeColumnName").getValueAsString();
It's clear from above example that lambda's are smart enough to handle the type of method parameters according to their anonymous inner class thus it makes the implementation of overridden method easy. Hope this will be helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With