我有下面的代码,它确实在没有 HashMap、HashSet 等的字符串中找到重复项,但我想要一个比这个更好的解决方案。请帮助我是 Java 编程的新手。我相信 Java 足够强大,可以提供 PS-这并不是我试图在 Java 集合中避免使用 HashMap 等。我只想要一个更时尚的解决方案
public class practice {
static void countWords(String st){
//split text to array of words
String[] words=st.split("\\s");
//frequency array
int[] fr=new int[words.length];
//init frequency array
for(int i=0;i<fr.length;i++)
fr[i]=0;
//count words frequency
for(int i=0;i<words.length;i++){
for(int j=0;j<words.length;j++){
if(words[i].equals(words[j]))
{
fr[i]++;
}
}
}
//clean duplicates
for(int i=0;i<words.length;i++){
for(int j=0;j<words.length;j++){
if(words[i].equals(words[j]))
{
if(i!=j) words[i]="";
}
}
}
//show the output
int total=0;
System.out.println("Duplicate words:");
for(int i=0;i<words.length;i++){
if(words[i]!=""){
System.out.println(words[i]+"="+fr[i]);
total+=fr[i];
}
}
System.out.println("Total words counted: "+total);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
countWords("apple banna apple fruit sam fruit apple hello hi hi hello hi");
}
}
您可以使用 Java8流countWords
在一行代码中编写整个方法(遵循内联注释):
static void countWords(String st){
Map<String, Long> wordsAndCounts =
Arrays.stream(st.split("\\s")). //Splt the string by space i.e., word
collect(Collectors.groupingBy( //Apply groupby
Function.identity(), //Map each word
Collectors.counting() //Count how many words
));
System.out.println(wordsAndCounts);
}
输出:
{banna=1, hi=3, apple=3, fruit=2, hello=2, sam=1}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句