使用集合的 Java Lambda 表示式


使用 lambda 表示式對列表中的元素進行排序 -

示例

 活動演示

import java.util.*;
public class Demo{
   public static void main(String[] args){
      ArrayList<Integer> my_arr = new ArrayList<Integer>();
      my_arr.add(190);
      my_arr.add(267);
      my_arr.add(12);
      my_arr.add(0);
      System.out.println("Before sorting, elements in the array list are : " + my_arr);
      Collections.sort(my_arr, (o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0);
      System.out.println("After sorting, elements in the array list are : " + my_arr);
   }
}

輸出

Before sorting, elements in the array list are : [190, 267, 12, 0]
After sorting, elements in the array list are : [267, 190, 12, 0]

一個名為 Demo 的類包含一個主函式。在這裡,使用“add”函式建立一個 arraylist 並新增元素。使用 sort 函式對元素進行排序,並且條件表示式決定當元素小於、大於或等於彼此時在螢幕上顯示什麼。

使用 lambda 表示式對 treemap 的元素進行排序 -

示例

 活動演示

import java.util.*;
public class Demo{
   public static void main(String[] args){
      TreeMap<Integer, String> my_treemap = new TreeMap<Integer, String>((o1, o2) -> (o1 > o2) ? -1 :       (o1 < o2) ? 1 : 0);
      my_treemap.put(56, "Joe");
      my_treemap.put(43, "Bill");
      my_treemap.put(21, "Charolette");
      my_treemap.put(33, "Jonas");
      System.out.println("The treemap contains the following elements : " + my_treemap);
   }
}

輸出

The treemap contains the following elements : {56=Joe, 43=Bill, 33=Jonas, 21=Charolette}

一個名為 Demo 的類包含一個主函式。在這裡,定義了一個 treemap,並且還編寫了條件表示式。使用“put”函式將元素新增到 treemap,並且將它們列印到控制檯上。

更新時間:2020 年 7 月 4 日

721 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.