Сортировка слов в массиве
у меня есть массив слов полученный из строки, как мне отсортировать слова в этом массиве по количеству гласных в нем?
public class MyLine {
private final String line;
public MyLine(String line) {
this.line = line;
}
public void vowelsCount(){
if(line == null){
throw new IllegalArgumentException("the word cannot be null!");
}
Pattern vowels = Pattern.compile("(?iu)[ауоыиэяюёе]");
Matcher matcher = vowels.matcher(line);
int vowelsCounter = 0;
while (matcher.find()) {
vowelsCounter++;
}
System.out.println("Результат: " + vowelsCounter + " гласных");
}
public void sortWords(){
Pattern vowels = Pattern.compile("(?iu)[ауоыиэяюёе]");
String[] words = line.split("\\s+");
for (int i = 0; i < words.length; i++) {
Matcher matcher = vowels.matcher(words[i]);
int vowelsCounter = 0;
while (matcher.find()) {
vowelsCounter++;
}
System.out.println("в слове: " + "'" + words[i] + "'" + " " + vowelsCounter + " гласная(гласных)");
}
}
public static void main(String[] args) {
MyLine example = new MyLine("ввод гласных букв");
example.vowelsCount();
example.sortWords();
}
}
Ответы (3 шт):
Автор решения: Adm123
→ Ссылка
- Введите отдельный класс для слова. Что-то вроде
class Word implements Comparable<Word> {
private String content;
public Word(String str) {
content = str;
}
public int getVowelsCount() {
//тут подсчет гласных в слове
return 25;
}
public String getContent() {
return content;
}
@Override
public int compareTo(Word o) {
return getVowelsCount() - o.getVowelsCount();
}
}
- Класс MyLine переработатйте во что-то вроде
class MyLine {
private final String line;
public MyLine(String line) {
this.line = line;
}
public List<String> sortWords(){
return Arrays.stream(line.split("\\s+"))
.map(str -> new Word(str))
.sorted()
.map(Word::getContent)
.collect(Collectors.toList());
}
public void printSortedList() {
System.out.println(sortWords());
}
}
Автор решения: JavaJunior
→ Ссылка
Example:
private static final Pattern pattern = Pattern.compile("[aeiouy]");
public static void main(String args[]) throws SocketException {
List<String> list = Arrays.asList("tree", "dog", "population", "revision", "fire");
list.sort(Comparator.comparing((i -> getValue(i))));
}
private static Integer getValue(String string) {
Matcher matcher = pattern.matcher(string);
int i = 0;
while (matcher.find()) {
i++;
}
return i;
}
Автор решения: Alex Rudenko
→ Ссылка
Имеет смысл сохранить массив слов как поле класса MyLine с соответствующим геттером, отсортировать его в методе sortByVowelCount.
Для подсчёта гласных можно использовать метод Stream::count для потока Stream<MatchResult>, который возвращается из метода Matcher::results в Java 9:
class MyLine {
private final String line;
private String[] words;
private static final Pattern VOWELS = Pattern.compile("(?iu)[aeiouаяеэёоиыую]");
public MyLine(String line) {
this.line = line;
this.words = line.split("\\s+");
}
public void sortByVowelCount() {
Arrays.sort(this.words, Comparator.comparingLong(
s -> VOWELS.matcher(s).results().count()
));
}
public String[] getWords() {
return this.words;
}
}
Тест:
MyLine line = new MyLine("Здравствуйте я тётушка Чарли из Бразилии");
line.sortByVowelCount();
System.out.println(Arrays.toString(line.getWords()));
// -> [я, из, Чарли, Здравствуйте, тётушка, Бразилии]