簡體   English   中英

對數組值進行排序,使它們對應於正在排序的其他數組(當它實際上沒有改變時)

[英]Sorting array values so they correspond to other array being sorted (when it's actually unchanged)

我對 Java 完全陌生,這個問題可能很簡單,但我真的需要幫助,因為我一直在努力尋找解決這個問題的任何可能的解決方案。

首先,一個簡短的例子來描述我的問題。 假設我有兩個數組列表:

// prices
[14, 2, 1, 10]

// ID numbers which correspond to these prices
[0, 1, 2, 3]

我的目標是對這些 ID 進行排序,以便它們對應於按升序排序的隨機整數。 換句話說,結果應該是:

// IDs sorted so they correspond to prices being in ascending order
[2, 1, 3, 0]

並且隨機整數數組應該保持不變。

是否可以? 你能幫我想想怎么做嗎?

假設“ID 號碼”實際上是第一個數組的索引,如示例中所示,那么您可以這樣排序:

int[] prices = { 14, 2, 1, 10 };
int[] idNumbers = { 0, 1, 2, 3 };

int[] sorted = Arrays.stream(idNumbers).boxed()
        .sorted(Comparator.comparingInt(i -> prices[i]))
        .mapToInt(Integer::intValue).toArray();
System.out.println(Arrays.toString(sorted));

輸出

[2, 1, 3, 0]

不幸的是,Java 的運行時庫沒有提供使用Comparator (或原始等價物)對原始數組進行排序的sort方法,因此在流式傳輸時對值進行裝箱和拆箱是最簡單的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM