java8实现List排序

  • 数值集合排序

    List list = Lists.newArrayList(3, 1, 2, -1);
    // 正序
    list.sort(Integer::compareTo);
    list.forEach((i) -> System.out.println(i));
    // 倒叙
    list.sort(Comparator.reverseOrder());
    list.forEach((i) -> System.out.println(i));
    // 正序
    list.sort(Comparator.naturalOrder());
    list.forEach((i) -> System.out.println(i));
    
  • 根据对象中的某个属性进行排序

    Orange orange = new Orange();
    orange.setWeight(1.34);
    Orange orange1 = new Orange();
    orange1.setWeight(1.2);
    Orange orange2 = new Orange();
    orange2.setWeight(2.34);
    List list = Lists.newArrayList(orange, orange1, orange2);
    // 正序
    // weight属性为基本类型
    list1.sort((Orange s, Orange o) -> s.getWeight() > o.getWeight() ? 1 : s.getWeight() == o.getWeight() ? 0 : -1);
    // weight属性为封装类型
    list1.sort((o1,o2)->o1.getWeight().compareTo(o2.getWeight()));
    // 2.34-1.34-1.2
    list1.forEach((o) -> System.out.println(o.getWeight()));
    // 倒叙
    // weight属性为基本类型
    list1.sort((Orange s, Orange o) -> o.getWeight() > s.getWeight() ? 1 : o.getWeight() == s.getWeight() ? 0 : -1);
    // weight属性为封装类型
    list1.sort((o1,o2)->o2.getWeight().compareTo(o1.getWeight()));
    //1.2-1.34-2.34
    list1.sort((Orange s, Orange o) -> o.getWeight().compareTo(s.getWeight()));
    list1.forEach((o) -> System.out.println(o.getWeight()));
    

更多文章:
点击跳转CSDN博客
点击跳转简书博客
公众号:代码小搬运
代码小搬运.jpg

你可能感兴趣的:(#,Java8)