MST
星途 面试题库

面试题:Java中Map接口常用方法的实际应用

假设你有一个需求,要统计一段英文文本中每个单词出现的次数,并按出现次数从高到低输出。请使用Java的Map接口相关方法实现这个功能,简述实现思路并给出核心代码片段。
25.1万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 首先将英文文本按单词进行拆分。
  2. 使用Map<String, Integer>来存储每个单词及其出现的次数,其中键为单词,值为出现次数。
  3. 遍历拆分后的单词数组,若Map中已存在该单词,则将其对应的值加1;若不存在,则将该单词加入Map并设值为1。
  4. Map中的数据转换为List,并根据单词出现次数进行排序。
  5. 最后按从高到低的顺序输出单词及其出现次数。

核心代码片段

import java.util.*;

public class WordCount {
    public static void main(String[] args) {
        String text = "this is a test this is another test";
        String[] words = text.split(" ");

        Map<String, Integer> wordCountMap = new HashMap<>();
        for (String word : words) {
            wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
        }

        List<Map.Entry<String, Integer>> list = new ArrayList<>(wordCountMap.entrySet());
        list.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));

        for (Map.Entry<String, Integer> entry : list) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}