java 8 排序反转_Java 8 排序小结

1、概述

首先,让我们先定义一个简单的实体类:

@Data

public class Human {

private String name;

private int age;

public Human() {

super();

}

public Human(final String name, final int age) {

super();

this.name = name;

this.age = age;

}

}

2、不使用Lambda表达式的基本排序

在Java 8之前,对集合进行排序要为Comparator创建一个匿名内部类用来排序:

new Comparator() {

@Override

public int compare(Human h1, Human h2) {

return h1.getName().compareTo(h2.getName());

}

}

简单地用它来对Human实体列表进行排序:

@Test

public void test() {

List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));

Collections.sort(humans, new Comparator() {

@Override

public int compare(Human h1, Human h2) {

return h1.getName().compareTo(h2.getName());

}

});

Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));

}

3、使用Lambda表达式的基本排序

根据Lambda表达式的介绍,我们现在可以不使用匿名内部类,只使用简单实用的语义就可以得到相同的结果。

(final Human h1, final Human h2) -> h1.getName().compareTo(h2.getName());

类似地,我们现在可以像之前那样来测试它的行为:

@Test

public void test() {

List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));

humans.sort((Human h1, Human h2) -> h1.getName().compareTo(h2.getName()));

Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));

}

注意:我们同样使用新的sort API,这个API在Java 8里被添加到java.util.List ——而不是旧的Collections.sort API。

4、没有类型定义( Type Definitions)的基本排序

我们通过不指定类型定义来进一步简化表达式 ——编译器自己可以进行类型判断:

(h1, h2) -> h1.getName().compareTo(h2.getName())

测试仍然很相似:

@Test

public void test() {

List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));

humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));

Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));

}

5、使用静态方法的引用来排序

下面我们将要使用带有静态方法引用的Lambda表达式去进行排序。

首先,我们要定义compareByNameThenAge方法 ——这个方法拥有与Comparator对象里的compareTo方法完全相同的签名:

public static int compareByNameThenAge(Human lhs, Human rhs) {

if (lhs.name.equals(rhs.name)) {

return lhs.age - rhs.age;

} else {

return lhs.name.compareTo(rhs.name);

}

}

现在,我们要使用这个引用去调用humans.sort方法:

humans.sort(Human::compareByNameThenAge);

最终结果是一个使用静态方法作为Comparator的有效的排序集合:

@Test

public void test() {

List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));

humans.sort(Human::compareByNameThenAge);

Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));

}

6、提取Comparator进行排序

我们可以通过使用实例方法的引用和Comparator.comparing方法来避免定义比较逻辑——它会提取和创建一个基于那个函数的Comparable。

我们准备使用getName() getter方法去建造Lambda表达式并通过name对列表进行排序:

@Test

public void test() {

List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));

Collections.sort(humans, Comparator.comparing(Human::getName));

Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));

}

7、反转排序

JDK 8同样提供了一个有用的方法用来反转Comparator(reverse Comparator)——我们可以快速地利用它来反转我们的排序:

@Test

public void test() {

List humans = Lists.newArrayList(

new Human("Sarah", 10), new Human("Jack", 12));

Comparator comparator = (h1, h2) -> h1.getName().compareTo(h2.getName());

humans.sort(comparator.reversed());

Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));

}

8、多条件排序

比较操作的Lambda表达式不一定都是这么简单的——我们同样可以编写更复杂的表达式,比如先根据name后根据age来对实体进行排序:

@Test

public void test() {

List humans = Lists.newArrayList(

new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));

humans.sort((lhs, rhs) -> {

if (lhs.getName().equals(rhs.getName())) {

return lhs.getAge() - rhs.getAge();

} else {

return lhs.getName().compareTo(rhs.getName());

}

});

Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));

}

9、多条件组合排序

同样的比较逻辑——先根据name进行排序其次是age,同样可以通过Comparator新的组合支持来实现。

从JDK 8开始,我们现在可以把多个Comparator链在一起(chain together)去建造更复杂的比较逻辑:

@Test

public void test() {

List humans = Lists.newArrayList(

new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));

humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));

Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
排序是一种常见的排序算法,具有稳定性高、效率高等优点。下面介绍一下使用Java实现的小根堆排序。 首先,我们需要定义一个小根堆类,用于存储待排序的数据。该类需要包含以下几个方法: 1. `Heap()`:构造函数,用于初始化小根堆。 2. `insert(int val)`:插入操作,将一个新的元素插入到小根堆中。 3. `deleteMin()`:删除操作,删除小根堆中的最小元素,并返回该元素的值。 4. `size()`:获取小根堆中元素的个数。 5. `isEmpty()`:判断小根堆是否为空。 接下来,我们就可以使用小根堆对待排序的数据进行排序了。具体的步骤如下: 1. 将待排序的数据存入小根堆中。 2. 依次从小根堆中删除最小元素,并将其存入数组中。 3. 最后,将数组反转,即可得到排序后的结果。 下面是具体的Java代码实现: ```java public class HeapSort { public static void heapSort(int[] arr) { Heap heap = new Heap(arr.length); for (int i = 0; i < arr.length; i++) { heap.insert(arr[i]); } for (int i = 0; i < arr.length; i++) { arr[i] = heap.deleteMin(); } // 反转数组 reverse(arr); } // 反转数组 private static void reverse(int[] arr) { int left = 0; int right = arr.length - 1; while (left < right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } // 小根堆类 static class Heap { private int[] heap; private int size; public Heap(int capacity) { heap = new int[capacity + 1]; size = 0; } public void insert(int val) { if (size == heap.length - 1) { throw new RuntimeException("Heap is full"); } int i = ++size; while (i != 1 && val < heap[i / 2]) { heap[i] = heap[i / 2]; i /= 2; } heap[i] = val; } public int deleteMin() { if (isEmpty()) { throw new RuntimeException("Heap is empty"); } int min = heap[1]; int last = heap[size--]; int i = 1; int child = 2; while (child <= size) { if (child < size && heap[child] > heap[child + 1]) { child++; } if (last > heap[child]) { heap[i] = heap[child]; i = child; child *= 2; } else { break; } } heap[i] = last; return min; } public int size() { return size; } public boolean isEmpty() { return size == 0; } } } ``` 使用该算法对数组进行排序: ```java int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}; HeapSort.heapSort(arr); System.out.println(Arrays.toString(arr)); // 输出 [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值