让我们首先创建一个带有字符串元素的列表。列表中的某些元素为空:
List<String> list = Arrays.asList("Jack", null, "Thor", null, "Loki", "Peter", null, "Hulk");
现在,对上面的列表进行排序,并使用nullsFirst首先将null放置:
list.sort(Comparator.nullsFirst(String::compareTo));
以下是对列表进行排序的示例,该列表首先将空值放在首位:
import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Demo { public static void main(String... args) { List<String> list = Arrays.asList("Jack", null, "Thor", null, "Loki", "Peter", null, "Hulk"); System.out.println("Initial List = "+list); list.sort(Comparator.nullsFirst(String::compareTo)); System.out.println("List placing nulls first = "+list); } }
输出结果
Initial List = [Jack, null, Thor, null, Loki, Peter, null, Hulk] List placing nulls first = [null, null, null, Hulk, Jack, Loki, Peter, Thor]