LambdaEx.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import java.util.List; import java.util.Arrays; import java.util.Comparator; import java.util.Collections; import java.util.function.Predicate; public class LambdaEx { // Old way: anonymous inner class public static void sortList(List<String> strs){ Collections.sort(strs, new Comparator<String>() { @Override public int compare(String a, String b) { return a.compareTo(b); } }); } public static void sortListLambda(List<String> strs){ // Using a lambda // Collections.sort(strs, (a, b) -> a.compareTo(b)); // Method reference is better here. Collections.sort(strs, String::compareTo); } public static String stringDoubler(String str, Predicate<String> strCond){ if (strCond.test(str)) return str + str; return str; } public static void main(String[] args){ List<String> strs = Arrays.asList("enterprise", "voyager", "discovery", "defiant"); System.out.println(strs); sortList(strs); System.out.println(strs); Collections.shuffle(strs); System.out.println(strs); sortListLambda(strs); System.out.println(strs); Predicate<String> isPalindrome = s -> s.equals(new StringBuilder(s).reverse().toString()); System.out.println(stringDoubler("racecar1", isPalindrome)); System.out.println(stringDoubler("racecar", isPalindrome)); Predicate<String> shortOrLongString = s -> s.length() < 3 || s.length() >9; System.out.println(stringDoubler("racecar", shortOrLongString)); System.out.println(stringDoubler("enterprise", shortOrLongString)); } } |