我有一个字符串数组,例如:
String[] words = {"apple", "peach", "apricot"};
如何以相应的频率打印每个字符串的首字母?
对于上面的例子,我的预期输出是:
a - 2
p - 1
我不知道该怎么做。请注意,字符串数组的内容是用户定义的,而不是在程序中预定义的。
这是我到目前为止所拥有的:
Scanner input = new Scanner(System.in);
String[] words = new String[20];
HashMap holder = new HashMap();
for (int i = 0; i < 5; i++) {
System.out.println("Enter word #" + (i + 1) + ": ");
words[i] = input.next();
}
for (int i = 0; i < 5; i++) {
for (int j = 1; j < 5; j++) {
if (words[i].charAt(0) == words[j].charAt(0)) {
freq += 1;
holder.put(words[i].charAt(0), freq);
}
}
}
答案 0 :(得分:1)
不想为你做功课,但不过在这里如何做到这一点......
Arrays.stream(wordArray)
.map(s -> s.charAt(0))
.collect(Collectors.groupingBy(c -> c, counting()))
.forEach((c, f) -> System.out.println(c + " - " + f));
在英语中,此代码:
答案 1 :(得分:0)
String[] test = { "apple", "clown", "banana", "ant", "batman" };
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < test.length; i++) {
if (map.containsKey(test[i].charAt(0))) {
map.put(test[i].charAt(0), map.get(test[i].charAt(0)) + 1);
} else {
map.put(test[i].charAt(0), 1);
}
}
for (Entry<Character, Integer> entry : map.entrySet()) {
System.out.println("" + entry.getKey() + " - " + entry.getValue());
}
答案 2 :(得分:0)
我能够修复它,这就是我所做的:
for (int i = 0; i < 20; i++){
System.out.println("Enter word #" + (i+1) +": ");
words[i] = input.next();
if (map.containsKey(words[i].charAt(0)))
{
map.put(words[i].charAt(0), (int)map.get(words[i].charAt(0))+ 1);
}
else
{
map.put(words[i].charAt(0), 1);
}
}
答案 3 :(得分:0)
private static void getStringInUpperCaseUsingStreams(Scanner sc2)
{
String[] str= sc2.nextLine().split(" ");
Arrays.stream(str).map(s-> s.substring(0, 1).toUpperCase()+ s.substring(1))
.forEach(s-> System.out.print(s+" "));
}