In general, I need to count the number of vowels in the n lines entered and sort them in ascending / descending order. To do this, I first translated String to Char, where I ran through all the letters and put a counter that counts the number of vowels. Next, Char put it back into the String and here I need to do the sorting, I can't figure out how to do it, tell me :)

import java.util.Scanner; public class projFour { public static void main(String[] args) { Scanner input = new Scanner(System.in); int row_val = 0, g = 1, localvar = 0; String temp; System.out.print("Enter row value: "); if(input.hasNextInt()){ row_val = input.nextInt(); } String[] a = new String[row_val + 1]; String[] c = new String[row_val + 1]; System.out.println("Enter " + row_val + " lines"); for (int i = 0; i < row_val + 1; i++){ if (input.hasNextLine()){ a[i] = input.nextLine(); } } char[] vowels = {'a','o','i','y','u','e'}; for (int i = 1; i < row_val + 1; i++) { char[] chars = a[i].toCharArray(); int k = 0; for (int j = 0; j < chars.length; j++){ for (int x = 0; x < vowels.length; x++) { if (chars[j] == vowels[x]) { k++; } } } //System.out.println("Odd val = " + k); String b = new String(chars); c[g] = b; System.out.println("String ========= " + c[g]); if (localvar > k) { temp = c[g - 1]; c[g - 1] = c[g]; c[g] = temp; localvar = k; } else { localvar = k; } g++; } for (int i = 1; i < row_val + 1; i++) { System.out.println("Sorted = " + c[i]); } } } 

    1 answer 1

    To sort the elements according to certain criteria, it is not necessary to implement the sorting algorithm, it is enough to write only your comparator. This is done very simply:

     // функция возвращающая количество гласных букв Function<String, Integer> getCount = new Function<String, Integer>() { // коллекция содержащая гласные буквы private Set<Character> set = new HashSet<>(Arrays.asList('а', 'е', 'у', 'ы', 'о', 'я')); @Override public Integer apply(String s) { int count = 0; for (int i = 0; i < s.length(); i++) count += set.contains(s.charAt(i)) ? 1 : 0; return count; } }; Comparator<String> comparator = (s1, s2) -> Integer.compare(getCount.apply(s1), getCount.apply(s2)); List<String> stringList = Arrays.asList("ааа", "я", "вв"); // сортировка по возврастанию частоты гласных букв // если требуется обратный порядок то нужно написать comparator.reversed() Collections.sort(stringList, comparator); 
    • And it can be somehow easier, all the same I am a beginner in java and it is desirable to do this by sorting, otherwise there’s nothing yet clear except for the hashset and the loop: D - Stab Ones
    • one
      carry the implementation of the function getCount into a static method, and implement the comparator through an anonymous or internal class, it will turn out without lambdas longer, but a little clearer. - Artem Konovalov