zoukankan      html  css  js  c++  java
  • Java8 新特性笔记

    Lambda表达式

    	public void test01() {
    		Comparator<Integer> comparator1 = new Comparator<Integer>() {
    
    			@Override
    			public int compare(Integer o1, Integer o2) {
    				return Integer.compare(o1,  o2);
    			}
    			
    		};
    		
    		TreeSet<Integer> treeSet1 = new TreeSet<>(comparator1); 
    		treeSet1.add(2);
    		treeSet1.add(3);
    		treeSet1.add(7);
    		treeSet1.add(1);
    		treeSet1.add(8);
    		
    		System.out.println(treeSet1);
    //[1, 2, 3, 7, 8]
    
    		
    		Comparator<Integer> comparator2 = (x, y) -> Integer.compare(x,  y);
    		TreeSet<Integer> treeSet2 = new TreeSet<>(comparator1); 
    		treeSet2.add(2);
    		treeSet2.add(3);
    		treeSet2.add(7);
    		treeSet2.add(1);
    		treeSet2.add(8);
    		
    		System.out.println(treeSet2);
    //[1, 2, 3, 7, 8]
    
    	}
    

    过滤并打印数据

        	public void test02() {
    		List<Integer> list = new ArrayList<>();
    		for (int i  = 0; i < 10; i++) {
    			list.add(i);
    		}
    		list.stream().filter((i) -> i > 5).forEach(System.out:: println);;
    	}
    

    以上代码输出如下

    6
    7
    8
    9
    

    limit用法

    	public void test03() {
    		List<Integer> list = new ArrayList<>();
    		for (int i  = 0; i < 10; i++) {
    			list.add(i);
    		}
    		list.stream()
    		.filter((i) -> i > 5)
    		.limit(2)
    		.forEach(System.out:: println);;
    	}
    

    打印结果如下

    6
    7
    
    

    map用法

    	public void test04() {
    		List<Integer> list = new ArrayList<>();
    		for (int i  = 0; i < 10; i++) {
    			list.add(i);
    		}
    		list.stream()
    		.filter((i) -> i > 5)
    		.map(Integer::floatValue)
    		.limit(2)
    		.forEach(System.out:: println);;
    	}
    

    打印结果如下

    6.0
    7.0
    

    函数式接口

    @FunctionalInterface
    public interface MyFunction<T> {
    	public String getValue(T t);
    }
    
    public class Main {
    
    	public static void main(String[] args) {
                    //以下两种方式等价
    		System.out.println(toUpperCase(new MyFunction<String>() {
    			
    			@Override
    			public String getValue(String t) {
    				return t.toUpperCase();
    			}
    		}, "hello world"));
    		
    		System.out.println(toUpperCase((t) -> t.toUpperCase(), "Hello world"));
    	}
    
    	private static String toUpperCase (MyFunction<String> myFunction, String str) {
    		return myFunction.getValue(str);
    	}
    }
    
  • 相关阅读:
    linux 复 带进度条
    frp配置
    zookeeper_service 出错 java.lang.NoClassDefFoundError: org/I0Itec/zkclient/exception/ZkNoNodeException
    zookeeper_service 出错 ........... are only available on JDK 1.5 and higher
    推荐eclipse插件Properties Editor
    使用ab对nginx进行压力测试
    Linux搭建Snmp服务
    第一个python程序
    如何执行Python代码
    pycharm 的调试模式 MAC版
  • 原文地址:https://www.cnblogs.com/umgsai/p/9900418.html
Copyright © 2011-2022 走看看