我们能否使用 Java 中的 Lambda 来对列表进行排序?


是的,我们可以使用 Lambda 对列表进行排序。我们首先创建一个字符串列表

List<String> list = Arrays.asList("LCD","Laptop", "Mobile", "Device", "LED", "Tablet");

现在,使用 Lambda 进行排序,在其中我们将使用 compareTo()

Collections.sort(list, (String str1, String str2) -> str2.compareTo(str1));

以下是在 Java 中使用 Lambda 对列表进行排序的一个示例

示例

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String... args) {  
      List<String> list = Arrays.asList("LCD","Laptop", "Mobile", "Device", "LED", "Tablet");
      System.out.println("List = "+list);
      Collections.sort(list, (String str1, String str2) -> str2.compareTo(str1));
      System.out.println("Sorted List = "+list);
   }
}

输出

List = [LCD, Laptop, Mobile, Device, LED, Tablet]
Sorted List = [Tablet, Mobile, Laptop, LED, LCD, Device]

更新于:2019 年 7 月 30 日

709 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.