method-reference

What is the equivalent lambda expression for System.out::println

安稳与你 提交于 2019-11-26 05:18:13
I stumbled upon the following Java code which is using a method reference for System.out.println class SomeClass{ public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9); numbers.forEach(System.out::println); } } } What is the equivalent lambda expression for System.out::println ? The method reference System.out::println will evaluate System.out first, then create the equivalent of a lambda expression which captures the evaluated value. Usually, you would use o->System.out.println(o) to achieve the same as the method reference, but this lambda

Comparator.reversed() does not compile using lambda

社会主义新天地 提交于 2019-11-25 21:39:40
I have a list with some User objects and i'm trying to sort the list, but only works using method reference, with lambda expression the compiler gives an error: List<User> userList = Arrays.asList(u1, u2, u3); userList.sort(Comparator.comparing(u -> u.getName())); // works userList.sort(Comparator.comparing(User::getName).reversed()); // works userList.sort(Comparator.comparing(u -> u.getName()).reversed()); // Compiler error Error: com\java8\collectionapi\CollectionTest.java:35: error: cannot find symbol userList.sort(Comparator.comparing(u -> u.getName()).reversed()); ^ symbol: method

Is method reference caching a good idea in Java 8?

做~自己de王妃 提交于 2019-11-25 18:59:59
Consider I have code like the following: class Foo { Y func(X x) {...} void doSomethingWithAFunc(Function<X,Y> f){...} void hotFunction(){ doSomethingWithAFunc(this::func); } } Suppose that hotFunction is called very often. Would it then be advisable to cache this::func , maybe like this: class Foo { Function<X,Y> f = this::func; ... void hotFunction(){ doSomethingWithAFunc(f); } } As far as my understanding of java method references goes, the Virtual Machine creates an object of an anonymous class when a method reference is used. Thus, caching the reference would create that object only once