HashMap по гласным
Запись в map слов из списка из файла, где ключ - количество гласных в слове, а значение - список слов, в которых присутствует получаенное количество гласных Есть метод, который ищет согласные
public static int[] getCountVowelToOffer(String[] offers) {
int[] result = new int[offers.length];
String pattern = "[а, е, ё, и, о, у, ы, э, ю, я]";
for (int i = 0; i < offers.length; i++) {
result[i] = offers[i].length() - offers[i].toLowerCase().replaceAll(pattern, "").length();
}
return result;
}
помогите реализовать мапу
Map<Integer, List> findMap = new HashMap<>();
int finalCount = count;
Files.readAllLines(Paths.get("file name"), Charset.defaultCharset())
.stream().collect(Collectors.toList()).forEach(word -> {
int number = finalCount;
if (getCountVowelToOffer(array).equals(finalCount)) findMap.get(number).add(word);
else {
List<String> listResult= new ArrayList<>();
listResult.add(word);
findMap.put(number, listResult);
}
});
Ответы (2 шт):
Автор решения: Дмитрий
→ Ссылка
Например, так
public static Map<Integer, List<String>> getCountVowelMap(String ... offers) {
final Set<Integer> vowels = "аеёийоуыэюя".chars().boxed().collect(Collectors.toSet());
final Map<Integer, List<String>> findMap = new HashMap<>();
for (String offer : offers) {
Integer countVowel = (int)offer.chars().filter(ch -> vowels.contains(ch)).count();
if (findMap.containsKey(countVowel)) findMap.get(countVowel).add(offer);
else {
List<String> list = new ArrayList<>();
list.add(offer);
findMap.put(countVowel, list);
}
}
return findMap;
}
Автор решения: IR42
→ Ссылка
Легко сделать с помощью Collectors.groupingBy
// вообще й не гласная
static private final Pattern vowelPattern = Pattern.compile("[аеёийоуыэюя]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
public static int countVowels(String s) {
/* java 8
int count = 0;
Matcher m = vowelPattern.matcher(s);
while (m.find()) count++;
return count;
*/
// java 9+
return (int) vowelPattern.matcher(s).results().count();
}
public static Map<Integer, List<String>> getMap(String filename) throws IOException {
return Files.readAllLines(Paths.get(filename), Charset.defaultCharset())
.stream().collect(Collectors.groupingBy(s -> countVowels(s)));
}