• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package com.uber.mylib;
2 
3 import java.util.Collections;
4 import java.util.Comparator;
5 import java.util.List;
6 import java.util.function.BiFunction;
7 import java.util.function.Function;
8 import javax.annotation.Nullable;
9 
10 /** Code that uses Java 8 lambdas */
11 @SuppressWarnings("UnusedVariable") // This is sample code
12 public class Lambdas {
13 
14   @FunctionalInterface
15   interface RetNullableFunction {
16 
17     @Nullable
getVal()18     Object getVal();
19   }
20 
testLambda()21   public static void testLambda() {
22     RetNullableFunction p =
23         () -> {
24           return null;
25         };
26     p.getVal();
27   }
28 
29   @FunctionalInterface
30   interface NonNullParamFunction {
31 
takeVal(Object x)32     String takeVal(Object x);
33   }
34 
35   @FunctionalInterface
36   interface NullableParamFunction {
37 
takeVal(@ullable Object x)38     String takeVal(@Nullable Object x);
39   }
40 
testNonNullParam()41   static void testNonNullParam() {
42     NonNullParamFunction n = (x) -> x.toString();
43     NonNullParamFunction n2 = (@Nullable Object x) -> (x == null) ? "null" : x.toString();
44     NullableParamFunction n3 = (@Nullable Object x) -> (x == null) ? "null" : x.toString();
45     NullableParamFunction n4 = (x) -> (x == null) ? "null" : x.toString();
46   }
47 
testBuiltIn()48   static void testBuiltIn() {
49     java.util.function.Function<String, String> foo = (x) -> x.toString();
50     BiFunction<String, Object, String> bar = (x, y) -> x.toString() + y.toString();
51     Function<String, Object> foo2 = (x) -> null;
52   }
53 
54   static class Size {
Size(int h, int w)55     public Size(int h, int w) {
56       this.height = h;
57       this.width = w;
58     }
59 
60     public final int height;
61     public final int width;
62   }
63 
testSort(List<Integer> intList, List<Size> sizeList)64   static void testSort(List<Integer> intList, List<Size> sizeList) {
65     Collections.sort(
66         intList,
67         (a, b) -> {
68           return (b - a);
69         });
70     Collections.sort(
71         intList,
72         (a, b) -> {
73           return a;
74         });
75     Collections.sort(
76         sizeList,
77         (a, b) -> {
78           int aPixels = a.height * a.width;
79           int bPixels = b.height * b.width;
80           if (bPixels < aPixels) {
81             return -1;
82           }
83           if (bPixels > aPixels) {
84             return 1;
85           }
86           return 0;
87         });
88   }
89 
testLambdaExpressionsAreNotNull()90   static Comparator<Integer> testLambdaExpressionsAreNotNull() {
91     return (a, b) -> {
92       return (b - a);
93     };
94   }
95 }
96