Reputation: 13
my arraylist :
"LVL:100 MONEY:1489 MANA: 42,1",
"LVL:67 MONEY:389 MANA: 33,5",
"LVL:47 MONEY:4229 MANA: 59,7",
"LVL:120 MONEY:1189 MANA: 94,5",
"LVL:150 MONEY:189 MANA: 19,2",
so I want it to sorted by value of MONEY
"LVL:47 MONEY:4229 MANA: 59,7",
"LVL:100 MONEY:1489 MANA: 42,1",
"LVL:120 MONEY:1189 MANA: 94,5",
"LVL:67 MONEY:389 MANA: 33,5",
"LVL:150 MONEY:189 MANA: 19,2",
Upvotes: 0
Views: 85
Reputation: 2202
Here is my attempt using Streams API. I make a new Comparator to give to sorted method in order to sort the money based on where it appears in the string.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SortMoney {
public static void main(String[] args) {
List<String> playerstats = Arrays.asList("LVL:100 MONEY:1489 MANA: 42,1",
"LVL:67 MONEY:389 MANA: 33,5",
"LVL:47 MONEY:4229 MANA: 59,7",
"LVL:120 MONEY:1189 MANA: 94,5",
"LVL:150 MONEY:189 MANA: 19,2");
List<String> sortedPlayerStates = playerstats.stream()
.map(data -> data.split(":"))
.sorted((o1, o2) -> {
int a = Integer.parseInt(o1[2].split(" ")[0]);
int b = Integer.parseInt(o2[2].split(" ")[0]);
if (a > b) {
return -1;
} else if (b > a) {
return 1;
} else {
return 0;
}
})
.map(data -> String.join(":", data))
.collect(Collectors.toList());
sortedPlayerStates.forEach(System.out::println);
}
}
Let me know if this is the result you want.
Edit: changed the code to store in variable in case you want to manipulate it later.
Upvotes: 3