Java程序对列表进行排序,并在最后放置空值
让我们首先创建一个带有字符串元素的列表。列表中的某些元素为空:
List<String> list = Arrays.asList("Jack", null, "Thor", null, "Loki", "Peter", null, "Hulk");
现在,对上面的列表进行排序,并在nullsLast的最后放置null。
list.sort(Comparator.nullsLast(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.nullsLast(String::compareTo)); System.out.println("List placing nulls in the end = "+list); } }
输出结果
Initial List = [Jack, null, Thor, null, Loki, Peter, null, Hulk] List placing nulls in the end = [Hulk, Jack, Loki, Peter, Thor, null, null, null]