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

Time:11-25

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 ,

CodePudding user response:

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]", ""))));

CodePudding user response:

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

CodePudding user response:

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]
  • Related