获取字符串中单词出现的次数

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);
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值