Java Sort List with Collections sort - Java 147

Java Sort List with Collections Sort – Java 147

Java Sort List with Collections Sort

在 Java 中對資料進行排序,提供 Collections sort 方法操作排序,預設會按升序對集合進行排序,當資料需要按特定順序排列,可以實作 Comparator 接口,使用傳統方式或 Lambda 表達式來實作其功能, Collections Class Sort 提供了預設比較器和建立自定義比較器,對資料進行排序,本篇增加了範例,並透過單元測試來驗證產出結果。

public static <T extends Comparable<? super T>> void sort(List<T> list) {
}

public static <T> void sort(List<T> list, Comparator<? super T> c) {
}

檔案目錄

./
   +- src
       +- test
       |   +- org
       |       +- ruoxue
       |           +- java_147
       |               +- collection
       |                   +- sort
       |                       +- SortListCollectionsSortTest.java   

單元測試

Sort with Collections Class 提供不同類型的資料進行排序,使用預設或自定義比較器,排序集合中的元素。

Fruit

建立 Fruit 類別,覆寫 toString ,定義屬性和方法,用來建立一個物件。

	@NoArgsConstructor
	@Getter
	@Setter
	@Builder
	public static class Fruit implements Comparable<Fruit> {

		private String name;
		private double quantity;
		private int type;

		public Fruit(String name, double quantity, int type) {
			this.name = name;
			this.quantity = quantity;
			this.type = type;
		}

		public String toString() {
			ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.JSON_STYLE);
			builder.appendSuper(super.toString());
			builder.append("name", name);
			builder.append("quantity", quantity);
			builder.append("type", type);
			return builder.toString();
		}

		@Override
		public int compareTo(Fruit o) {
			int result = this.name.compareTo(o.name);
			if (result == 0)
				result = Double.compare(this.quantity, o.quantity);
			return result;
		}
	}

sort

Sort with Collections Class 建立一個 List ,增加三個元素,使用 Collections sort 方法,依照預設比較器,由小到大,升序對集合進行排序。

	@Test
	public void sort() {
		Fruit orange = new Fruit("Orange", -1, 3);
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		List<Fruit> list = List<Fruit> list = Arrays.asList(orange, mango, peach);
		System.out.println(list);

		Collections.sort(list);
		System.out.println(list);
		assertThat(list).containsExactly(mango, orange, peach);
	}
[{"name":"Orange","quantity":-1.0,"type":3}, {"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Peach","quantity":3.0,"type":1}]
[{"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}, {"name":"Peach","quantity":3.0,"type":1}]

sortWithReverseOrder

Sort with Collections Class 建立一個 List ,增加三個元素,使用 Collections sort 方法,依照預設反向比較器,由大到小,降序對集合進行排序。

	@Test
	public void sortWithReverseOrder() {
		Fruit orange = new Fruit("Orange", -1, 3);
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		List<Fruit> list = List<Fruit> list = Arrays.asList(orange, mango, peach);
		System.out.println(list);

		Collections.sort(list, Comparator.reverseOrder());
		System.out.println(list);
		assertThat(list).containsExactly(peach, orange, mango);
	}
[{"name":"Orange","quantity":-1.0,"type":3}, {"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Peach","quantity":3.0,"type":1}]
[{"name":"Peach","quantity":3.0,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}, {"name":"Mango","quantity":1.7976931348623157E308,"type":1}]

sortWithComparator

Sort with Collections Class 建立一個 List ,增加三個元素,使用 Collections sort 方法,依照自定義比較器,由小到大,升序對集合進行排序。

	@Test
	public void sortWithComparator() {
		Fruit orange = new Fruit("Orange", -1, 3);
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		List<Fruit> list = List<Fruit> list = Arrays.asList(orange, mango, peach);
		System.out.println(list);

		Collections.sort(list, (o1, o2) -> Double.compare(o1.quantity, o2.quantity));
		System.out.println(list);
		assertThat(list).containsExactly(orange, peach, mango);
	}
[{"name":"Orange","quantity":-1.0,"type":3}, {"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Peach","quantity":3.0,"type":1}]
[{"name":"Orange","quantity":-1.0,"type":3}, {"name":"Peach","quantity":3.0,"type":1}, {"name":"Mango","quantity":1.7976931348623157E308,"type":1}]

sortWithComparing

Sorting Collections Sort in Java 建立一個 List ,增加三個元素,使用 Collections sort 方法,依照自定義比較器,由小到大,升序對集合進行排序。

	@Test
	public void sortWithComparing() {
		Fruit orange = new Fruit("Orange", -1, 3);
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		List<Fruit> list = List<Fruit> list = Arrays.asList(orange, mango, peach);
		System.out.println(list);

		Collections.sort(list, Comparator.comparing(Fruit::getType).thenComparing(Fruit::getQuantity));
		System.out.println(list);
		assertThat(list).containsExactly(peach, mango, orange);
	}
[{"name":"Orange","quantity":-1.0,"type":3}, {"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Peach","quantity":3.0,"type":1}]
[{"name":"Peach","quantity":3.0,"type":1}, {"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}]

sortWithMultipleConditions

Sorting Collections Sort in Java 建立一個 List ,增加三個元素,使用 Collections sort 方法,依照多個自定義比較器,由小到大,升序對集合進行排序。

	protected static Comparator<Fruit> nameComparator = new Comparator<Fruit>() {
		@Override
		public int compare(Fruit o1, Fruit o2) {
			return o1.name.compareTo(o2.name);
		}
	};

	protected static Comparator<Fruit> quantityComparator = (o1, o2) -> Double.compare(o1.quantity, o2.quantity);

	@Test
	public void sortWithMultipleConditions() {
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		Fruit orange = new Fruit("Orange", -1, 3);
		List<Fruit> list = Arrays.asList(mango, peach, orange);
		System.out.println(list);

		Collections.sort(list, nameComparator.thenComparing(quantityComparator));
		System.out.println(list);
		assertThat(list).containsExactly(mango, orange, peach);
	}
[{"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Peach","quantity":3.0,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}]
[{"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}, {"name":"Peach","quantity":3.0,"type":1}]

sortWithNull

Sorting Collections Sort in Java 建立一個 List ,增加三個元素及一個 null 元素,使用 Collections sort 方法,依照自定義比較器, null 元素放在第一個,由小到大,升序對集合進行排序。

	@Test
	public void sortWithNull() {
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		Fruit orange = new Fruit("Orange", -1, 3);
		List<Fruit> list = Arrays.asList(mango, peach, orange, null);
		System.out.println(list);

		Collections.sort(list, (s1, s2) -> {
			if (s1 == null) {
				return s2 == null ? 0 : -1;
			} else if (s2 == null) {
				return 1;
			}
			return s1.compareTo(s2);
		});
		System.out.println(list);
		assertThat(list).containsExactly(null, mango, orange, peach);
	}
[{"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Peach","quantity":3.0,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}, null]
[null, {"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}, {"name":"Peach","quantity":3.0,"type":1}]

sortWithNullsFirst

Sorting Collections Sort in Java 建立一個 List ,增加三個元素及一個 null 元素,使用 Collections sort 方法,依照 nullsFirst 比較器, null 元素放在第一個,由小到大,升序對集合進行排序。

	@Test
	public void sortWithNullsFirst() {
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		Fruit orange = new Fruit("Orange", -1, 3);
		List<Fruit> list = Arrays.asList(mango, peach, orange, null);
		System.out.println(list);

		Collections.sort(list, Comparator.nullsFirst(Comparator.comparing(s -> s)));
		System.out.println(list);
		assertThat(list).containsExactly(null, mango, orange, peach);
	}
[{"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Peach","quantity":3.0,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}, null]
[null, {"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}, {"name":"Peach","quantity":3.0,"type":1}]

sortWithNullsLast

Sorting Collections Sort in Java 建立一個 List ,增加三個元素及一個 null 元素,使用 Collections sort 方法,依照 nullsLast 比較器, null 元素放在最後個,由小到大,升序對集合進行排序, Java Sort List Collections Sort Examples 提供範例參考。

	@Test
	public void sortWithNullsLast() {
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		Fruit orange = new Fruit("Orange", -1, 3);
		List<Fruit> list = Arrays.asList(mango, peach, orange, null);
		System.out.println(list);

		Collections.sort(list, Comparator.nullsLast(Comparator.comparing(s -> s)));
		System.out.println(list);
		assertThat(list).containsExactly(mango, orange, peach, null);
	}
[{"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Peach","quantity":3.0,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}, null]
[{"name":"Mango","quantity":1.7976931348623157E308,"type":1}, {"name":"Orange","quantity":-1.0,"type":3}, {"name":"Peach","quantity":3.0,"type":1}, null]

SortListCollectionsSortTest.java

Sorting Collections Sort in Java 新增單元測試,驗證 Java Sort List Collections Sort Examples 是否符合預期。

package org.ruoxue.java_147.collection.sort;

import static org.assertj.core.api.Assertions.assertThat;

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

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.junit.Test;

import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

public class SortListCollectionsSortTest {

	@NoArgsConstructor
	@Getter
	@Setter
	@Builder
	public static class Fruit implements Comparable<Fruit> {

		private String name;
		private double quantity;
		private int type;

		public Fruit(String name, double quantity, int type) {
			this.name = name;
			this.quantity = quantity;
			this.type = type;
		}

		public String toString() {
			ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.JSON_STYLE);
			builder.appendSuper(super.toString());
			builder.append("name", name);
			builder.append("quantity", quantity);
			builder.append("type", type);
			return builder.toString();
		}

		@Override
		public int compareTo(Fruit o) {
			int result = this.name.compareTo(o.name);
			if (result == 0)
				result = Double.compare(this.quantity, o.quantity);
			return result;
		}
	}

	@Test
	public void sort() {
		Fruit orange = new Fruit("Orange", -1, 3);
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		List<Fruit> list = Arrays.asList(orange, mango, peach);
		System.out.println(list);

		Collections.sort(list);
		System.out.println(list);
		assertThat(list).containsExactly(mango, orange, peach);
	}

	@Test
	public void sortWithReverseOrder() {
		Fruit orange = new Fruit("Orange", -1, 3);
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		List<Fruit> list = Arrays.asList(orange, mango, peach);
		System.out.println(list);

		Collections.sort(list, Comparator.reverseOrder());
		System.out.println(list);
		assertThat(list).containsExactly(peach, orange, mango);
	}

	@Test
	public void sortWithComparator() {
		Fruit orange = new Fruit("Orange", -1, 3);
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		List<Fruit> list = Arrays.asList(orange, mango, peach);
		System.out.println(list);

		Collections.sort(list, (o1, o2) -> Double.compare(o1.quantity, o2.quantity));
		System.out.println(list);
		assertThat(list).containsExactly(orange, peach, mango);
	}

	@Test
	public void sortWithComparing() {
		Fruit orange = new Fruit("Orange", -1, 3);
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		List<Fruit> list = Arrays.asList(orange, mango, peach);
		System.out.println(list);

		Collections.sort(list, Comparator.comparing(Fruit::getType).thenComparing(Fruit::getQuantity));
		System.out.println(list);
		assertThat(list).containsExactly(peach, mango, orange);
	}

	protected static Comparator<Fruit> nameComparator = new Comparator<Fruit>() {
		@Override
		public int compare(Fruit o1, Fruit o2) {
			return o1.name.compareTo(o2.name);
		}
	};

	protected static Comparator<Fruit> quantityComparator = (o1, o2) -> Double.compare(o1.quantity, o2.quantity);

	@Test
	public void sortWithMultipleConditions() {
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		Fruit orange = new Fruit("Orange", -1, 3);
		List<Fruit> list = Arrays.asList(mango, peach, orange);
		System.out.println(list);

		Collections.sort(list, nameComparator.thenComparing(quantityComparator));
		System.out.println(list);
		assertThat(list).containsExactly(mango, orange, peach);
	}

	@Test
	public void sortWithNull() {
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		Fruit orange = new Fruit("Orange", -1, 3);
		List<Fruit> list = Arrays.asList(mango, peach, orange, null);
		System.out.println(list);

		Collections.sort(list, (s1, s2) -> {
			if (s1 == null) {
				return s2 == null ? 0 : -1;
			} else if (s2 == null) {
				return 1;
			}
			return s1.compareTo(s2);
		});
		System.out.println(list);
		assertThat(list).containsExactly(null, mango, orange, peach);
	}

	@Test
	public void sortWithNullsFirst() {
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		Fruit orange = new Fruit("Orange", -1, 3);
		List<Fruit> list = Arrays.asList(mango, peach, orange, null);
		System.out.println(list);

		Collections.sort(list, Comparator.nullsFirst(Comparator.comparing(s -> s)));
		System.out.println(list);
		assertThat(list).containsExactly(null, mango, orange, peach);
	}

	@Test
	public void sortWithNullsLast() {
		Fruit mango = new Fruit("Mango", Double.MAX_VALUE, 1);
		Fruit peach = new Fruit("Peach", 3, 1);
		Fruit orange = new Fruit("Orange", -1, 3);
		List<Fruit> list = Arrays.asList(mango, peach, orange, null);
		System.out.println(list);

		Collections.sort(list, Comparator.nullsLast(Comparator.comparing(s -> s)));
		System.out.println(list);
		assertThat(list).containsExactly(mango, orange, peach, null);
	}
}

心得分享

Java Sort List Collections Sort Examples 排序是指使用特定標準以特定順序排列資料,可以對不同類型的資料進行排序,像是字串、數字和物件,提供了幾種 Sort 常見方法的操作範例,在應用上相當廣泛,熟悉 Sorting Collections Sort in Java 這些方法的操作,可以讓排序依照不同的需求,更簡易、快速地實現功能。

發佈留言