test/tools/javac/lambda/MethodReference01.java

changeset 0
959103a6100f
equal deleted inserted replaced
-1:000000000000 0:959103a6100f
1 /*
2 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24 /*
25 * @test
26 * @bug 8003280
27 * @summary Add lambda tests
28 * use method reference to sort list elements by field
29 * @author Brian Goetz
30 * @author Maurizio Cimadamore
31 * @run main MethodReference01
32 */
33
34 import java.util.*;
35
36 public class MethodReference01 {
37
38 interface Getter<U, T> {
39 public U get(T t);
40 }
41
42 static class Foo {
43 private Integer a;
44 private String b;
45
46 Foo(Integer a, String b) {
47 this.a = a;
48 this.b = b;
49 }
50
51 static Integer getA(Foo f) { return f.a; }
52 static String getB(Foo f) { return f.b; }
53 }
54
55 public static <T, U extends Comparable<? super U>>
56 void sortBy(List<T> s, final Getter<U, T> getter) {
57 Collections.sort(s, new Comparator<T>() {
58 public int compare(T t1, T t2) {
59 return getter.get(t1).compareTo(getter.get(t2));
60 }
61 });
62 };
63
64 public static void main(String[] args) {
65 List<Foo> c = new ArrayList<Foo>();
66 c.add(new Foo(2, "Hello3!"));
67 c.add(new Foo(3, "Hello1!"));
68 c.add(new Foo(1, "Hello2!"));
69 checkSortByA(c);
70 checkSortByB(c);
71 }
72
73 static void checkSortByA(List<Foo> l) {
74 sortBy(l, Foo::getA);
75 int oldA = -1;
76 for (Foo foo : l) {
77 if (foo.a.compareTo(oldA) < 1) {
78 throw new AssertionError();
79 }
80 }
81 }
82
83 static void checkSortByB(List<Foo> l) {
84 sortBy(l, Foo::getB);
85 String oldB = "";
86 for (Foo foo : l) {
87 if (foo.b.compareTo(oldB) < 1) {
88 throw new AssertionError();
89 }
90 }
91 }
92 }

mercurial