public class CountWordInString {
public static Map<String,Integer> wor(String words){
//创建Map集合,key是字符串中的字符,value是字符的个数
Map<String,Integer> re= new HashMap<>();
//使用split()方法,将字符串以空格的方式分开
String [] wordArray=words.split(" ");
//将字符串遍历
for(String word: wordArray){
//判断字符串中是否有单词存在,存在:将之前的数字加一,不存在:默认为一
if(re.containsKey(word)){
Integer count=re.get(word);
count++;
re.put(word,count);
}else {
re.put(word,1);
}
}
return re;
}
}
public class Test {
public static void main(String[] args) {
String a ="If you want to change your fate I think you must come to the ujiuye to learn java";
//调用方法
Map<String, Integer> wor = CountWordInString.wor(a);
System.out.println(wor);
}
}
实现结果:
{think=1, fate=1, ujiuye=1, learn=1, want=1, change=1, I=1, come=1, your=1, the=1, java=1, must=1, to=3, If=1, you=2}
获取TXT文件中单词出现的次数
public class Test {
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\java\\idea-date\\springboot\\src\\main\\java\\com\\aaa\\util\\test\\1.txt"));
String s = bufferedReader.readLine();
Map<String, Integer> wor = CountWordInString.wor(s);
System.out.println(wor);
}
}
使用Stream API获取单词出现的次数
public class Me {
public static void main(String[] args) {
List<String> strings=Arrays.asList("abc","","bc","efg","abcd","","jkl","abcd","abcd","abcd","efg","efg","efg");
//使用filter⽅法的设置的条件过滤出空元素
//Collectors(收集器).groupingBy根据分类函数对元素进行分组,并在Map中返回结果。
strings.stream().filter((String str) -> str.length() > 0).collect(Collectors.groupingBy((x) -> x)).
values().stream().map(x-> x.get(0)+"="+x.size()).forEach(System.out::println);
}
}