首页  

java8 Lambda 实例     所属分类 java8 浏览量 1492
java.util.IntSummaryStatistics
java.util.function.Predicate
java.util.stream.Collectors

sort map reduce filter stream collect


	
		// 替代匿名类

		Runnable r = () -> {
			System.out.println("hello");
		};
		r.run();
		
		r = () -> System.out.println("hello2") ;
		r.run();
			
		
		List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");	
		
		// 按字符串长度排序
		languages.sort(Comparator.comparing(String::length));
		System.out.println(languages);
		
                // 按字符串长度倒排
		languages.sort(Comparator.comparing(String::length).reversed());

		System.out.println(languages);


		Predicate startsWithJ = (n) -> n.startsWith("J");
		Predicate fourLetterLong = (n) -> n.length() == 4;
		
		// Predicate 组合
		languages.stream()
		      .filter(startsWithJ.and(fourLetterLong))
		      .forEach((n) -> System.out.println("\nName, which starts with 'J' and four letter long is : " + n));
		
		
		// Map 和 Reduce
		List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);	
		costBeforeTax.stream().map((cost) -> cost + .12*cost).forEach(System.out::println);

		double bill = costBeforeTax.stream().map((cost) -> cost + .12*cost)
                .reduce((sum, cost) -> sum + cost).get();
        System.out.println("Total : " + bill);
		
		
		List strList = Arrays.asList("a","ab","","abc","xyz");
		List filtered = strList.stream().filter(x -> x.length()> 2).collect(Collectors.toList());
        System.out.printf("Original List : %s, filtered list : %s %n", strList, filtered);

		// 对集合中每个元素应用函数
		List G7 = Arrays.asList("USA", "Japan", "France", "Germany","Italy", "U.K.","Canada");
        String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(", "));
        System.out.println(G7Countries);
		
			
        // 过滤集合中重复元素
		List numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
		List distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
		System.out.println(distinct);
		
		
		// 计算 最大值,最小值,和及平均值
		List primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
		IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
		System.out.println("max=" + stats.getMax());
		System.out.println("min=" + stats.getMin());
		System.out.println("sum=" + stats.getSum());
		System.out.println("avg=" + stats.getAverage());


完整代码
https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/java8/LambdaTest2.java

上一篇     下一篇
aerospike增加节点

aerospike删除节点

The java.util.concurrent Synchronizer Framework 翻译

富爸爸穷爸爸 摘录

会计学习指南

Java8 parallelStream 并行处理实例及注意点