-3
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 ,

  • 3
    because the `0` comes before the `g` when alphabetically comparing `"10q"` and `"1g"`. – f1sh Nov 24 '22 at 18:50
  • For Strings, their natural order is lexicographical, so just like in most dictionaries `aa` comes before `b`, the `10` comes before `2` `3` .. `9`. – Pshemo Nov 24 '22 at 19:58

3 Answers3

0

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]", ""))));
Anon
  • 385
  • 2
  • 6
0

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
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

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]