Есть задание, где сначала надо вычислить слова с длинной слова больше среднего значения, a потом отсортировать их так, чтобы сначала шли слова с числами.
Сделал что-то типа этого. Как упростить и выполнить сортировку? Как сначала вывести слова с цифрами, а потом просто слова?
вот мой пример:
public List<String> convertText(String text) {
String[] words = text.split("\\p{P}?[ \\t\\n\\r]+"); // split by whitespace
int count = 0;
double sum = 0;
for (String word : words) {
double wordLength = word.length();
sum += wordLength;
count++;
}
final double average = sum / count;
List<String> list = Arrays.stream(words).filter(s -> s.length()>= average).collect(Collectors.toList());
for (int i = 0; i < list.size(); i++) {
if (!list.get(i).matches(".*\\d+.*")){
list.add(list.size() - 1, list.remove(i));
}
}
return list;
}
Я о Java, конечно, мало чего знаю, но рабочее решение показать могу. Написал я простой код, в котором есть temporary массивы, - это проще для понимания.
public List<String> convertText(String text) {
String[] words = text.split("\\p{P}?[ \\t\\n\\r]+");
int count = 0;
double sum = 0;
for (String word : words) {
double wordLength = word.length();
sum += wordLength;
count++;
}
final double average = sum / count;
List<String> list = Arrays.stream(words).filter(s -> s.length()>= average).collect(Collectors.toList());
// Create a list with words containing digits
final List<String> wordsContainingDigits = list.stream()
.filter(w -> w.matches(".*\\d+.*"))
.collect(Collectors.toList());
// Remove all the words that contain
// digits from the initial list
IntStream.range(0, wordsContainingDigits.size() - 1)
.forEach(idx -> list.remove(idx));
// Create the instance of a new list, which would
// in future would be sorted.
List<String> newList = new ArrayList<String>();
// Fill the new array with the words containing digits first,
// and then with the other.
Stream.of(wordsContainingDigits, list).forEach(newList::addAll);
return newList;
}
Пишите свой компаратор.
При этом учтите, что если сравнивать числа как строки, то результат будет не правильны. Хотя вы не указали какой результат вам нужен
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости