Learner
Learner

Reputation: 41

Arrange characters of an array in the order they appear in the string java

I have an array of some characters from a string and the string. I want to arrange the characters in the order they appear in the string. For example: Array a consists of s, o , e and the string is house. I want the result to be "ose". I tried using the Arrays.sort method but it returns the alphabets in the alphabetical order.

Upvotes: 3

Views: 373

Answers (3)

forpas
forpas

Reputation: 164069

Create a custom comperator:

class MyComperartor implements Comparator<Character> {
    private static String pattern = "house";

    public int compare(Character c1, Character c2) {
        return pattern.indexOf(c1) - pattern.indexOf(c2);
    }
}

and sort the array:

Character[] array = { 'e', 's', 'o'};
Arrays.sort(array, new MyComperartor());
System.out.println(Arrays.toString(array));

will print:

[o, s, e]

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56423

You could use this overload of sort:

Arrays.sort(chars, Comparator.comparingInt(str::indexOf));

given chars is of type Character[] and str is the String.

Upvotes: 6

m.antkowicz
m.antkowicz

Reputation: 13571

If you have in the array only characters from a string you can actually count how much of every character do you have in the array and then iterate over the string adding to the new collection specific count of that character

String string = "house";
List<String> chars = Arrays.asList("s", "e", "o", "o")
Map<String, Integer> characterCount = initializeMapWithCharsAndZeroes(chars);

for(String character : chars) {
    characterCount.put(character, characterCount.get(characterCount)+1);
}

for(String character : string .split("")) {
    for(int i = 0; i < characterCount.get(character); i++) {
        System.out.println(string);
    }
}

Upvotes: 0

Related Questions