Fun with method references
Rémi Forax
forax at univ-mlv.fr
Thu Aug 5 07:26:19 PDT 2010
Le 05/08/2010 15:54, John Nilsson a écrit :
> On Wed, Aug 4, 2010 at 11:33 PM, Brian Goetz<brian.goetz at oracle.com> wrote:
>
>> Check this out -- this works with the latest prototype:
>> Arrays.sortBy(foos, Foo#getA); // sort by JavaBean property A
>>
> I'm wondering if this kind of thing will increase the demand for
> tuples in the language. So far it has been my experience that most
> uses of classes such as Pair<A,B> is better served by actually naming
> the attribute collection to something sensible. But with code like
> this I can see how a simple tuple would simplify things.
>
> So will
> Arrays.sortBy(foos, tuple(Foo#getA,Foo#getB))
> be good enough or would it be better with
> Arrays.sortBy(foos, (Foo#getA,Foo#getB)) // Standard parenthesis tuple syntax
> or
> Arrays.sortBy(foos, Foo#getA x Foo#getB) // Product combinator operator
>
> BR,
> John
>
John,
my advice here is to use the varargs syntax (with an
@SuppressWarnings("varargs"))
But it doesn't work with the current prototype.
Worst there is not lambda conversion between #int(String) and
Extractor<?,? super K>.
import java.util.List;
public class MyTest2 {
interface Extractor<U, T> {
public U get(T t);
}
static class Arrays {
public static <K extends Comparable<K>> void sortBy(List<K> c,
Extractor<Integer,? super K> extractor) { }
//public static <K extends Comparable<K>> void sortBy(List<K> c,
Extractor<?,? super K> extractor) { }
//public static <K extends Comparable<K>> void sortBy(List<K> c,
Extractor<?,? super K>... extractor) { }
}
public static void main(String[] args) {
List<String> list = java.util.Arrays.asList(args);
Arrays.sortBy(list, #(String s){s.length()});
}
}
Rémi
More information about the lambda-dev
mailing list