Lambda語法及例子
阿新 • • 發佈:2018-11-10
package com.example.pk.lambada; import org.assertj.core.util.Lists; import java.util.*; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; class Test{ public void TestTo(){ List<String> s1 = Arrays.asList("sss","DDDf","MDdss"); List<String> s2 =s1.stream().map(str->{ System.out.println(this.getClass().getName()); return str.toLowerCase(); }).collect(Collectors.toList()); s2.forEach(System.out::println); } } public class LambadaTest { public static void main(String[] args) { String[] m = {"ZZZ","sDSs","PySd"}; List<String> proName = Arrays.asList(m); // List<String> lowercaseNames1 = proName.stream().map(name-> name.toLowerCase()).collect(Collectors.toList()); // List<String> lowercaseNames1 = proName.stream().map(String::toLowerCase).collect(Collectors.toList()); // System.out.println(lowercaseNames1); Arrays.sort(m,Comparator.comparing(String::toLowerCase)); Integer[] h = {1,5,6,4,88,5,46,4}; // List<Integer> integerList = Arrays.asList(h); Arrays.sort(h); List<Integer> integerList = Arrays.asList(h); System.out.println(integerList); integerList.forEach(System.out::println); String waibu = "lambda :"; List<String> proStrs = Arrays.asList("Ni","Hao","Lambda"); List<String>execStrs = proStrs.stream().map(chuandi -> { Long zidingyi = System.currentTimeMillis(); return waibu + chuandi + " -----:" + zidingyi; }).collect(Collectors.toList()); execStrs.forEach(System.out::println); Test test = new Test(); test.TestTo(); List<Integer> integerList1 = Lists.newArrayList(1,null,5,45,null,8); integerList1.stream().filter(Objects::nonNull).count(); //使用Stream靜態方法建立Stream //<1> Stream<Integer> integerStream = Stream.of(1,5,6,8); //<2> Stream.generate(new Supplier<Double>() { public Double get(){ return Math.random(); } }); Stream.generate(() -> Math.random()); Stream.generate(Math::random); //轉換Stream //distinct 去重 filter 過濾 map 對Stream中包含使用給定的轉換函式進行轉換操作 integerList1.stream().limit(1); integerList1.stream().skip(4); List<Integer> nums = Lists.newArrayList(1,1,null,2,3,4,null,5,6,7,8,9,10); // List<Integer> numsWithoutNull = nums.stream().filter(num -> num != null). // collect(ArrayList::new, // ArrayList::add, // ArrayList::addAll); List<Integer> numsWithoutNull = nums.stream().filter(Objects::nonNull).collect(Collectors.toList()); numsWithoutNull.forEach(System.out::println); //reduce 引數兩個 1 上一次函式的返回值,2 stream中的元素 long d = nums.stream().filter(Objects::nonNull).reduce(0,(sum,item)->sum+item); System.out.println(d); //count、allMatch、anyMatch、findFirst、noneMatch、max、min System.out.println(nums.stream().allMatch(Objects::nonNull)); System.out.println(nums.stream().filter(Objects::nonNull).anyMatch(item -> item>6)); } }