public class LambdaPrac { /** * 迭代 */ @Test public void demo1(){ List list = Arrays.asList("jinx","timo","ez"); list.forEach(n -> System.out.println(n)); } /** * 函数式接口Predicate */ @Test public void demo2(){ List<String> list = Arrays.asList("jinx","timo","ez"); filter(list,(String str) -> str.startsWith("j")); } public static void filter(List<String> list, Predicate<String> condition){ for(String str : list){ if(condition.test(str)){ System.out.println(str + " "); } } } /** * lambda表达式中加入predicate */ @Test public void demo3(){ List<String> list = Arrays.asList("jinx","timo","ez"); Predicate<String> startWithJ = (n) -> n.startsWith("j"); Predicate<String> fourLetterLong = (n) -> n.length() == 4; list.stream().filter(startWithJ.and(fourLetterLong)).forEach(n -> System.out.println(n)); } /** * map的使用 */ @Test public void demo4(){ List<Integer> cost = Arrays.asList(100,200,300,400,500); cost.stream().map((c) -> c + 100).forEach(System.out::println); } /** * 对列表每个元素应用函数 */ @Test public void demo5(){ List<String> list = Arrays.asList("jinx","timo","ez"); String s = list.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(",")); System.out.println(list.stream().count()); System.out.println(s); } /** *求和 */ @Test public void demo6(){ List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29); System.out.println(primes.stream().reduce(Integer::sum).get()); } /** * 分组 */ @Test public void demo7(){ List<String> list = Arrays.asList("day", "walipo", "day", "walipo", "legeand", "day", "douwbo", "day", "day"); Map<String, Long> collect = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.out.println(collect); } }