美文网首页
lambda函数是变成对集合进行排序的几种方式

lambda函数是变成对集合进行排序的几种方式

作者: mordor | 来源:发表于2017-12-14 19:58 被阅读0次

    先来一个集合:

    List<Point> points = 
    Arrays.asList(
         new Point(1, 2),
         new Point(3, 2),
         new Point(4, 2),
         new Point(2, 2)
    );
    

    方式一:

    // 比较器方法
    Comparator<Point> byX = new Comparator<Point>() {
        @Override
        public int compare(Point p1, Point p2) {
              return Double.compare(p1.getX(), p2.getX());
        }
    };
    

    方式二(最简单):

    Comparator<Point> byX = Comparator.comparing(Point::getX);
    

    方式三(过时):

    Comparator<Point> byX = (p1, p2) -> Double.compare(p1.getX(), p2.getX());
    

    方式四:

    Function<Point, Double> keyExtractor = point -> point.getX();
    Comparator<Double> keyComparer = Double::compare;
    Comparator<Point> byX = (p1, p2) -> keyComparer.compare(keyExtractor.apply(p1), keyExtractor.apply(p2));
    

    方式五(方式四的进阶版推荐):

    // 封装一个比较的方法
    public static <T,U extends Comparable<U>> Comparator<T> comparing(Function<T,U> keyExtractor){
        return Comparator.comparing(keyExtractor::apply);
    }
    
    Function<Point, Double> keyExtractor = point -> point.getX();
    Comparator<Point> byX = comparing(keyExtractor);
    

    测试:

    System.out.println("排序前:" + points);
    points.sort(byX);
    System.out.println("排序后:" + points);
    

    测试结果:

    排序前:
    [java.awt.Point[x=1,y=2], 
     java.awt.Point[x=3,y=2], 
     java.awt.Point[x=4,y=2], 
     java.awt.Point[x=2,y=2]]
    排序后:
    [java.awt.Point[x=1,y=2], 
     java.awt.Point[x=2,y=2], 
     java.awt.Point[x=3,y=2], 
     java.awt.Point[x=4,y=2]]
    

    本文参考:《精通lambda表达式:java多核编程》

    相关文章

      网友评论

          本文标题:lambda函数是变成对集合进行排序的几种方式

          本文链接:https://www.haomeiwen.com/subject/mrrlwxtx.html