1 回答

TA贡献1757条经验 获得超7个赞
这就是如何使用 split 方法将字符串转换为字符串数组。我没有使用列表,因为我想向您展示一种稍微不同的方法来解决此问题。
我正在删除空格并将所有内容转换为小写。如果你想做的话,这取决于你。
Scanner input = new Scanner(System.in);
String userInput;
System.out.print("Enter a line of words: ");
userInput = input.nextLine().replace(" ", "").toLowerCase();
String[] userInputSplit = userInput.split(""); // Splits array
Arrays.sort(userInputSplit); // Sorts array
System.out.println(Arrays.toString(userInputSplit)); // Prints sorted array
// Checks for frequency of each letter using maps
Map<String, Integer> countMap = Arrays.stream(userInputSplit)
.collect(Collectors.toMap(Function.identity(), v -> 1, Integer::sum));
// Prints map
System.out.println("Frequency of words: " + countMap.toString());
输出:
Enter a line of words: The quick brown fox jumps over the lazy dog
[a, b, c, d, e, e, e, f, g, h, h, i, j, k, l, m, n, o, o, o, o, p, q, r, r, s, t, t, u, u, v, w, x, y, z]
Frequency of words: {a=1, b=1, c=1, d=1, e=3, f=1, g=1, h=2, i=1, j=1, k=1, l=1, m=1, n=1, o=4, p=1, q=1, r=2, s=1, t=2, u=2, v=1, w=1, x=1, y=1, z=1}
编辑:
就像@AndyTurner建议的那样,您也可以使用Collectors.counting()这使得语法更容易理解,但它将返回 Long 而不是 Integer
Map<String, Long> countMap = Arrays.stream(userInputSplit)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Collectors.counting本质上是
Map<String, Integer> countMap = Arrays.stream(userInputSplit)
.collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum));
使用 HashSet 和 Collections.Frequency:
HashSet<String> uniqueValues = new HashSet<String>(userInputList);
for (String value : uniqueValues) {
System.out.println("Frequency of " + value + " is: " + Collections.frequency(userInputList, value));
}
添加回答
举报