Sort String based on a pattern array of String

Viewed 75

I need to sort a string of words in an order those words are placed in the pattern array:

String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings", "Milkshake", "Coke"};

String s = "Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake"; // input string

Expect

"Burger Burger Burger Burger Fries Chicken Chicken Chicken Chicken Onionrings Onionrings Onionrings Milkshake Milkshake Milkshake Milkshake Coke Coke Coke Coke" // output string
4 Answers

You may use a List to be able to get index from word, then sort the words using these indexes

  • Get a List os the words to get them indexable
  • split your String into an array to be able to sort the words
  • sort them based on their indices in the List
  • join the words to get one String
// INPUTS
String s = "Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake";
String expect = "Burger Burger Burger Burger Fries Chicken Chicken Chicken Chicken Onionrings Onionrings Onionrings Milkshake Milkshake Milkshake Milkshake Coke Coke Coke Coke";
String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings",
    "Milkshake", "Coke"};

// Get the patterns a list to get the indexOf method
List<String> listPatterns = Arrays.asList(pattern);

// Split in words
String[] values = s.split(" ");

//Sort base on index in list
Arrays.sort(values, Comparator.comparing(listPatterns::indexOf));

// Rebuild a string by joining
String result = String.join(" ", values);

// true
System.out.println(result.equals(expect));

Since the question does not contain any code, I will only post a rough sketch of a solution.

I would approach the problem by splitting the String in a list of words, then use a Comparator to sort those words and re-join them with separating blanks.

A common way to write Comparators is to assign the both objects compared against each other an int-value, subtract one from the other and return that as the comparison result.

In the Comparator, I would use the index of the two words compared against each other in the pattern-array as base for comparison.

Try this.

String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings", "Milkshake", "Coke"};

// make pattern to index map. {Burger=0, Fries=1, Chicken=2, ...}
Map<String, Integer> patternMap = IntStream.range(0, pattern.length).boxed()
    .collect(Collectors.toMap(i -> pattern[i], Function.identity()));

// sort words using patternMap
String s = "Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake"; // input string
String[] result = Arrays.stream(s.split("\\s+"))
    .sorted(Comparator.comparing(word -> patternMap.get(word)))
    .toArray(String[]::new);

System.out.println(Arrays.toString(result));

output:

[Burger, Burger, Burger, Burger, Fries, Chicken, Chicken, Chicken, Chicken, Onionrings, Onionrings, Onionrings, Milkshake, Milkshake, Milkshake, Milkshake, Coke, Coke, Coke, Coke]

here is code to sort alphabetically

public class MainProgram {

    public static void main(String[] args) {
        String temp;
        String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings", "Milkshake", "Coke"};
          //Sorting the strings
        for (int i = 0; i < pattern.length; i++) 
        {
            for (int j = i + 1; j < pattern.length; j++) { 
                if (pattern[i].compareTo(pattern[j])>0) 
                {
                    temp = pattern[i];
                    pattern[i] = pattern[j];
                    pattern[j] = temp;
                }
            }
        }
      //Displaying the strings after sorting them based on alphabetical order
        System.out.print("Strings in Sorted Order:");
        for (int i = 0; i <= pattern.length - 1; i++) 
        {
            System.out.print(pattern[i] + ", ");
        }
        
    }

}
Related