zoukankan      html  css  js  c++  java
  • J2SE 8的Lambda --- Comparator

    		Person[] personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Person("Alice")};
    		
    		//1. 使用静态的比较器,比较的对象不能为null值
    		Arrays.sort(personArray, Comparator.comparing(Person::getName));
    		for (Person person : personArray) {
    			System.out.println(person.getName());
    		}
    		System.out.println();
    		
    		//2. 使用andThen,在第一层比较相同的情况下,使用andThen的比较器,  多次比较
    		personArray = new Person[]{new Person("Tom","A","Tom" ),new Person("Tom","B","Tom" ),new Person("Jack"),new Person("Alice")};
    		Arrays.sort(personArray, Comparator.comparing(Person::getName).thenComparing(Person::getFirstName).thenComparing(Person::getLastName));
    		for (Person person : personArray) {
    			System.out.println(person.getName()+"-"+person.getFirstName()+"-"+person.getLastName());
    		}
    		System.out.println();
    		
    		//3. 变体格式,指定具体比较的内容
    		personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Person("Alice")};
    		Arrays.sort(personArray, Comparator.comparing(Person::getName, (x,y)->Integer.compare(x.length(), y.length())));
    		for (Person person : personArray) {
    			System.out.println(person.getName());
    		}
    		System.out.println();
    		
    		//4.对于可能返回null的情况,使用nullsFirst和nullsLast适配器
    		personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Person("Alice"),new Person()};
    		Arrays.sort(personArray, Comparator.comparing(Person::getName, Comparator.nullsFirst(Comparator.naturalOrder())));
    		for (Person person : personArray) {
    			System.out.println(person.getName());
    		}
    		System.out.println();
    		
    		//5. 逆序比较 Comparator.comparing().reversed()
    		personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Person("Alice"),new Person()};
    		Arrays.sort(personArray, Comparator.comparing(Person::getName, Comparator.nullsFirst(Comparator.naturalOrder())).reversed());
    		for (Person person : personArray) {
    			System.out.println(person.getName());
    		}
    		System.out.println();
    		
    	

  • 相关阅读:
    [转]addEventListener() 方法,事件监听
    JavaScrpit判断横竖屏
    无法获得锁 /var/lib/dpkg/lock
    配置Meld为git的默认比较工具
    C#多线程之旅(7)——终止线程
    【SQL进阶】03.执行计划之旅1
    单问号和双问号
    聚集索引VS非聚集索引
    【T-SQL进阶】02.理解SQL查询的底层原理
    【T-SQL】系列文章全文目录(2017-06-26更新)
  • 原文地址:https://www.cnblogs.com/xiang--liu/p/9710388.html
Copyright © 2011-2022 走看看