利用Java Lambda Function实现的自定义排序逻辑(Comparator)

package java8;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Sorter {

	class Human {
	    private String name;
	    private int age;

	    public String getName() {
	    	return name;
	    }
	    
	    public Human() {
	    	
	    }
	    public int getAge() {
	    	return age;
	    }
	    
	    public Human(final String name, final int age) {
	        this.name = name;
	        this.age = age;
	    }
	}
	/* Jerry 2015-11-12 : should put this into instance method 
	 * This is what Lists.newArrayList does:

@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList() {
    return new ArrayList<E>();
}
So these two are basically the same, with using newArrayList having the advantage on not 
having to duplicate the generic type. This is very helpful on complex generics:

List<Map<X,List<Y>> list = new ArrayList<Map<X,List<Y>>();

List<Map<X,List<Y>> list = Lists.newArrayList();

No enclosing instance of type Sorter is accessible. Must qualify the allocation with an enclosing instance 
of type Sorter ( e.g X.new A() where x is an instance of Sorter )

*/
	
	public void sortTest(){
		List<Human> humans = new ArrayList<Human>();

		humans.add(new Human("Ethan", 7));
		humans.add(new Human("GrandMother", 61));
		humans.add(new Human("Jerry", 37));
		humans.add(new Human("Fairy", 38));
		humans.add(new Human("GrandFather", 60));
		
		Collections.sort(humans, new Comparator<Human>() {
			@Override
			public int compare(Human h1, Human h2) {
				return h1.getName().compareTo(h2.getName());
			}
		});
		
		System.out.println("list....");
		humans.forEach(n -> System.out.println("Name: " + n.getName() + " age: " + n.getAge()));
		
		Comparator<Human> com = (Human h1, Human h2) -> h1.getName().compareTo(h2.getName()) * (-1);
		
		humans.sort(com);
		
		System.out.println("again list....");
		humans.forEach(n -> System.out.println("Name: " + n.getName() + " age: " + n.getAge()));
		
	}
	
	public static void main(String[] args) {
		Sorter instance = new Sorter();
		instance.sortTest();
	}
}


展开阅读全文
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值