![](/img/trans.png)
[英]How would I separate one value of an array (for the entire array) into alphabetic and numeric characters, and then into separate arrays? (Java)
[英]Sorting two separate Java arrays by value of one array
我目前正在嘗試按值然后按字母名稱對兩個單獨的數組進行排序。 我怎樣才能做到這一點?
String[] players = new String[5];
int[]goalsByPlayer = new int[5];
players = {a, b, c, d, e};
goalsByPlayer = {3, 0, 0, 0, 0};
1. a 3 goals
2. b 0 goals
3. c 0 goals
4. d 0 goals
5. e 0 goals
如果我將目標c的數量更改為4,則該列表應為...
1. c 4 goals
2. a 3 goals
3. b 0 goals
4. d 0 goals
5. e 0 goals
請發送建議!
編輯:這是我編寫的代碼。
for (int w = 0; w < number; w++) {
goalsByPlayer[w] *= -1;
}
Arrays.sort(sort);
for (int w = 0; w < number; w++) {
goalsByPlayer[w] *= -1;
}
for (int p = 0; p < number; p++) {
System.out.println((p + 1) + ". " + players[p] + " " + goalsByPlayer[p] + " goals");
}
我只是不知道如何讓字符串匹配數組中的整數。
實際輸出:
1. a 4 goals
2. b 3 goals
3. c 0 goals
4. d 0 goals
5. e 0 goals
public static void main(String[] args) {
// Input data
String[] players = {"a","b","c","d","e"};
int[] goalsByPlayer = {3,0,0,4,0};
// Put all of them into Map
Map<String, Integer> unsortMap = new HashMap<>();
for (int i = 0; i < players.length; i++) {
unsortMap.put(players[i], goalsByPlayer[i]);
}
System.out.println("Unsort Map......");
printMap(unsortMap);
// Sort by value with reverse order
Map sorted = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println("\nSorted Map......By Value");
printMap(sorted);
}
// print a map
public static <K, V> void printMap(Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey()
+ " Value : " + entry.getValue());
}
}
產量
Unsort Map......
Key : a Value : 3
Key : b Value : 0
Key : c Value : 0
Key : d Value : 4
Key : e Value : 0
Sorted Map......By Value
Key : d Value : 4
Key : a Value : 3
Key : b Value : 0
Key : c Value : 0
Key : e Value : 0
將它們添加到地圖並使用Java 8中可用的流。
String[] players = { "a", "b", "c", "d", "e" };
int[] goalsByPlayer = { 3, 0, 0, 4, 0 };
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < players.length; i++) map.put(players[i], goalsByPlayer[i]);
Map<String, Integer> sortedMap = new LinkedHashMap<>();
map.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed()).forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));
for (String key : sortedMap.keySet()) System.out.println("Player: " + key + " goals: " + sortedMap.get(key));
這是輸出
Player: d goals: 4
Player: a goals: 3
Player: b goals: 0
Player: c goals: 0
Player: e goals: 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.