char[] tmpArr = T.toCharArray();

Here is the mistake, you can't use premitives with comparator. You need to convert it to Character[].

You could do something like below with Apache commons-lang:

char[] charArray = str.toCharArray();
Character[] tmpArr = ArrayUtils.toObject(charArray);

Here are some good ways to convert.

Answer from Krupal Shah on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › java › util › arrays_sort_char.htm
Java Arrays sort(char[] a) Method
The Java Arrays sort(char[]) method sorts the specified array of chars into ascending numerical order. This method using a Dual-Pivot Quicksort algorithm which breaks the array into subarrays, sorted them and then merged to give a sorted array.
Top answer
1 of 4
5
char[] tmpArr = T.toCharArray();

Here is the mistake, you can't use premitives with comparator. You need to convert it to Character[].

You could do something like below with Apache commons-lang:

char[] charArray = str.toCharArray();
Character[] tmpArr = ArrayUtils.toObject(charArray);

Here are some good ways to convert.

2 of 4
3

It looks like there is no auto unboxing to Character.

To be precise, primitive to object conversion at compile time is called boxing. Unboxing is the reverse way.
And yes Character/char provides an autoboxing feature but it doesn't work in this way. Here the primitives/wrapper counterparts are in an array or a list : so no boxing possible here.

That compiles :

char a = Character.valueOf('a'); // compile
Character aa  = 'a'; // compile

But that does not :

List<Character> charList = ...;
char[] charArray= ...;
charList = charArray; // doesn't compile
charArray = charList; // doesn't compile

How can I make this work?

Sorting an array of char with a specific Comparator is not conventional.
So not surprising that the Arrays API doesn't provide such a method.
Generally, Comparator and Comparable implementations rely only on the state of the compared objects to return the result, not on an external variable as in your example.
Similarly the Arrays API doesn't provide any method to create a Stream of char because streaming characters is also not a very conventional need.
So you don't have a straight built-in way to solve your issue.

In your situation, I would rely onArrays.stream(String.split()) to get a String for each character of the original String and I would apply the sort and finish with a joining :

String originalValue = "...";
String afterSortValue =
    Arrays.stream(originalValue.split(""))
          .sorted((o1, o2) -> {
                    Integer aPos = poses.get(o1);
                    Integer bPos = poses.get(o2);
                    if (aPos == null || bPos == null)
                      return 0;
                    return Integer.compare(aPos, bPos);
                  }
          )
         .collect(Collectors.joining());

This should be the most direct way without using external libraries.

Discussions

Sorting a char array in java - Stack Overflow
if you know how to sort an integer array, then do the same but change the type from int to char and the comparison method (if char1 < char2 thing). More on stackoverflow.com
🌐 stackoverflow.com
How can you manually sort a char array?
https://en.wikipedia.org/wiki/Sorting_algorithm Implement your own. Don't forget that char is actually a numeric data type and therefore can be compared and treated like int. More on reddit.com
🌐 r/javahelp
3
0
February 18, 2021
java - Sorting characters alphabetically in a String - Stack Overflow
In this case its alphabetically, ... to the character, with 'a' < 'b'. The only gotcha to look out for is mixed case, since 'z' < 'A'. To get around, this, you can use str.tolower(). I'd recommend you look up some basic sorting algorithms too. ... Save this answer. ... Show activity on this post. Your for loop is starting at 1 and it should be starting at zero: ... Save this answer. ... Show activity on this post. You can do this using Arrays.sort, if you ... More on stackoverflow.com
🌐 stackoverflow.com
sorting - Sort character array using java comparator - Stack Overflow
Sort a character array lexicographically with an additional condition that all c's comes before all b's. This could be done manually but I want to code it via inbuilt sorting using comparators. More on stackoverflow.com
🌐 stackoverflow.com
🌐
BeginnersBook
beginnersbook.com › 2014 › 07 › sorting-char-array-in-java-example
Sorting char array in Java example
September 11, 2022 - We have demonstrated two types of sorting in the program 1) Complete sorting using sort(char[] a) method 2) Sorting specified range of characters only using sort(char[] a, int fromIndex, int toIndex) method. import java.util.Arrays; class SortCharArray { public static void main(String[] args) ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › arrays-sort-in-java
Arrays.sort() in Java - GeeksforGeeks
Sorts object arrays using their natural ordering or a provided Comparator. It uses Dual-Pivot QuickSort for primitives and TimSort for objects (optimized for performance). ... import java.util.Arrays; class Geeks{ public static void main(String[] ...
Published: August 27, 2026
🌐
W3Schools
w3schools.com › java › ref_arrays_sort.asp
Java Arrays sort() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... The sort() method sorts an array in ascending order.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › java › util › arrays_sort_char_index.htm
Java.util.Arrays.sort() Method
The following example shows the usage of java.util.Arrays.sort() method. package com.tutorialspoint; import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // initializing unsorted char array char aArr[] = ...
🌐
How to do in Java
howtodoinjava.com › home › java sorting › sort a string alphabetically in java (arrays.sort, streams)
Sort a String Alphabetically in Java (Arrays.sort, Streams)
1 month ago - The order of Arrays.sort() is the order of the char values in the Unicode table. All uppercase ASCII letters have smaller values than the lowercase letters, and digits and the space character come even earlier.
🌐
DataCamp
datacamp.com › doc › java › sort
Java Array sort()
The Arrays.sort() method in Java is a utility provided by the java.util.Arrays class to sort arrays of various data types. It is widely used to organize data in ascending order, making it easier to search, analyze, or display. The Arrays.sort() method can be applied to arrays of primitive data ...
🌐
YouTube
youtube.com › watch
How to sort the charArray? | sort(char[] a) method of Java.util.Arrays Class - YouTube
How to sort the charArray? | sort(char[] a) method of Java.util.Arrays ClassClick the below link to download the Java Source code and PPT:https://drive.googl...
Published: October 31, 2019
Top answer
1 of 3
4

The problem is that if passing 'c' and 'b' makes the comparison return a negative value, then passing 'b' and 'c' should return a positive one (And your first version returns a negative number in that case instead). If the function doesn't return consistent results no matter the order of arguments, the sort algorithm is going to produce a garbage order.

Consider this version:

    public int compare(Character x, Character y) {
        if (x == 'c' && y == 'b') {
            return -1;
        } else if (x == 'b' && y == 'c') {
            return 1;
        } else {
            return x.compareTo(y);
        }
    }
2 of 3
1

You can add System.out.println() to understand how it work:

Code

import java.util.Arrays;
import java.util.Comparator;

public class Main {

    public static void main(String[] args) {
        String s = "abracadabra";
        int n = s.length();
        
        System.out.println("X Y\tX Y\t[if] VALUE");
        System.out.println();
        
        Character[] res = new Character[n];
        for (int i = 0; i < n; i++) {
            res[i] = s.charAt(i);
        }
        
        int min = 'a';
        
        Arrays.sort(res, new Comparator<Character>() {

            @Override
            public int compare(Character x, Character y) {
                System.out.print(y + " " + x + "\t" + (x-min) + " " + (y-min) + "\t");
                if(x == 'c' && y == 'b') {
                    System.out.println("true " + (y - x));
                    return y - x;
                }
                System.out.println("     " + (x - y));
                return x - y;
            }
        });
        System.out.println("#################################\nResult:\n" + Arrays.toString(res));
    }
}

Console:

X Y X Y   [if] VALUE

a b 1 0        1
b r 17 1       16
r a 0 17       -17
b a 0 1        -1
a a 0 0        0
b c 2 1   true -1
a c 2 0        2
c a 0 2        -2
a a 0 0        0
c d 3 2        1
r d 3 17       -14
b d 3 1        2
c a 0 2        -2
a a 0 0        0
a a 0 0        0
c b 1 2        -1
a b 1 0        1
a b 1 0        1
b r 17 1       16
d r 17 3       14
r r 17 17      0
c a 0 2        -2
a a 0 0        0
b a 0 1        -1
a a 0 0        0
#################################
Result:
[a, a, a, a, a, b, c, b, d, r, r]
🌐
Edureka
edureka.co › blog › character-array-in-java
Char Array In Java | Introduction To Character Arrays In Java | Edureka
July 5, 2024 - Java which is one of the best programming languages makes use of char array to hold data. In this article we would exploring everything that is there to know about them. Table of Content · Following pointers will be discussed in this article, Declaring Char Array · Initializing Char Array · Loops In Char Array · Length Of Char Array · Sorting A Char Array ·
🌐
Reddit
reddit.com › r/javahelp › sort char array method
r/javahelp on Reddit: sort char array method
May 19, 2022 -

Any tips towards sorting an array of character's into alphabetical order. I have all of the input I'm just having trouble with the method to sort it

Top answer
1 of 3
2
https://en.wikipedia.org/wiki/Sorting_algorithm While there is a built-in sorting, most likely the purpose of the exercise it to learn to write your own sorting algorithm. One of the simplest to program sorting algorithms is Bubble Sort and you should really try implementing this algorithm.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
YouTube
youtube.com › watch
How to Sort a Character Array in Ascending Order Using Java - YouTube
Learn how to sort a character array in ascending order using Java, including key concepts and example code to help you get started.---Disclaimer/Disclosure: ...
Published: November 18, 2024
Views: 17
🌐
GeeksforGeeks
geeksforgeeks.org › arrays-sort-in-java-with-examples
Arrays.sort() in Java with Examples | GeeksforGeeks
Another one allows sorting a specific part of the array by passing the starting and ending indices. Below is a simple example that uses the sort() method to arrange an array of integers in ascending order.
Published: November 11, 2024