简体   繁体   中英

Why 10 is in the beginning of an ArrayList after Sort() ? How to place 10 after 9?

String s = "vttqexwqgdc";
char[] ch = s.toCharArray();
int[] indices = {9, 5, 8, 0, 4, 3, 6, 10, 1, 2, 7};
ArrayList<String> list = new ArrayList<>();
for (int i = 0, j = 0; i < ch.length; i++, j++) {
    list.add((indices[j] + "" + ch[i]));
}
Collections.sort(list);
System.out.println(list); // **[0q, 10q, 1g, 2d, 3x, 4e, 5t, 6w, 7c, 8t, 9v], Here the 10q should be after 9
**String str = "";
for (String value : list) {
    str = str + value;
}
str = str.replaceAll("\\d", "");
System.out.println(str);

please help me how can i sort it, where i can place 10q after 9v.

Thank you Everyone

sorting the answer,

This works

list.sort((a, b) -> Integer.parseInt(a.replaceAll("[a-zA-Z]", "")) - Integer.parseInt(b.replaceAll("[a-zA-z]", "")));  

This is the same has the above but with the Comparator

list.sort(Comparator.comparingInt(a -> Integer.parseInt(a.replaceAll("[a-zA-Z]", ""))));

You need to use custom comparator which parses the integer value of the index:

Collections.sort(list, Comparator.comparingInt(
    c -> Integer.parseInt(c.substring(0, c.length() - 1))
));
// ...

Then the output is as follows:

[0q, 1g, 2d, 3x, 4e, 5t, 6w, 7c, 8t, 9v, 10q]
qgdxetwctvq

You should create the list after sorting. It is inefficient to convert strings to integers every time you compare them.

ArrayList<String> list = IntStream.range(0, ch.length)
    .boxed()
    .sorted(Comparator.comparing(i -> indices[i]))
    .map(i -> indices[i] + "" + ch[i])
    .collect(Collectors.toCollection(ArrayList::new));
System.out.println(list);

output

[0q, 1g, 2d, 3x, 4e, 5t, 6w, 7c, 8t, 9v, 10q]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM