【问题标题】:Sorting string occurrences from text file从文本文件中对出现的字符串进行排序
【发布时间】:2016-11-20 04:34:52
【问题描述】:

我已将文件中的字符串存储到 ArrayList 中,并使用 HashSet 来计算每个字符串的出现次数。

我希望列出前 5 个单词及其出现次数。我应该能够在不实现哈希表、树图等的情况下完成此操作。我该如何实现呢?

这是我的数组列表:

List<String> word_list = new ArrayList<String>();

        while (INPUT_TEXT1.hasNext()) {
            String input_word = INPUT_TEXT1.next();
            word_list.add(input_word);

        }

        INPUT_TEXT1.close();

        int word_list_length = word_list.size();



        System.out.println("There are " + word_list_length + " words in the .txt file");
        System.out.println("\n\n");

        System.out.println("word_list's elements are: ");



        for (int i = 0; i<word_list.size(); i++) {
                System.out.print(word_list.get(i) + "  ");

            }

        System.out.println("\n\n");

这是我的哈希集:

Set<String> unique_word = new HashSet<String>(word_list);

    int number_of_unique = unique_word.size();

    System.out.println("unique worlds are: ");

    for (String e : unique_word) {
        System.out.print(e + " ");

    }

    System.out.println("\n\n");


    String [] word = new String[number_of_unique];
    int [] freq = new int[number_of_unique];

    int count = 0;

    System.out.println("Frequency counts : ");

    for (String e : unique_word) {
        word[count] = e;
        freq[count] = Collections.frequency(word_list, e);



        System.out.println(word[count] + " : "+ freq[count] + " time(s)");
        count++;

    }

会不会是我想多了一步?提前致谢

【问题讨论】:

  • 创建一个内部类,比如 Z,它有两个字段 - word、count,它实现了Comparable&lt;Z&gt; 并覆盖了hashcode()equals() 方法。创建此类的实例集 - 如果集合包含对象,则获取它并增加计数。使用Collections.sort() 对其进行排序。你去吧。
  • 也就是说,Hashmap 可能是更好的方法
  • 在 Apache Commons 中有一个简单的实现,使用 HashBag

标签: java arraylist hashset


【解决方案1】:

您可以使用HashMap 来执行此操作(唯一的单词为key,频率为value),然后按照以下步骤中的相反顺序对values 进行排序:

(1) 用字词加载word_list

(2) 找出word_list中的唯一词

(3) 将唯一词存入HashMap,唯一词为key,频率为value

(4) 使用值(频率)对HashMap 进行排序

您可以参考以下代码:

public static void main(String[] args) {

        List<String> word_list = new ArrayList<>();
        //Load your words to the word_list here

        //Find the unique words now from list
        String[] uniqueWords = word_list.stream().distinct().
                                       toArray(size -> new String[size]);
        Map<String, Integer> wordsMap = new HashMap<>();
        int frequency = 0;

        //Load the words to Map with each uniqueword as Key and frequency as Value
        for (String uniqueWord : uniqueWords) {
            frequency = Collections.frequency(word_list, uniqueWord);
            System.out.println(uniqueWord+" occured "+frequency+" times");
            wordsMap.put(uniqueWord, frequency);
        }

       //Now, Sort the words with the reverse order of frequency(value of HashMap)
       Stream<Entry<String, Integer>> topWords = wordsMap.entrySet().stream().
         sorted(Map.Entry.<String,Integer>comparingByValue().reversed()).limit(5);

        //Now print the Top 5 words to console
        System.out.println("Top 5 Words:::");
        topWords.forEach(System.out::println);
 }

【讨论】:

    【解决方案2】:

    使用 java 8 并将所有代码放在一个块中。

     Stream<Map.Entry<String,Long>> topWords =
                words.stream()
                        .map(String::toLowerCase)
                        .collect(groupingBy(identity(), counting()))
                        .entrySet().stream()
                        .sorted(Map.Entry.<String, Long> comparingByValue(reverseOrder())
                                .thenComparing(Map.Entry.comparingByKey()))
                        .limit(5);
    

    遍历流

    topWords.forEach(m -> {
                System.out.print(m.getKey() + " : "+ m.getValue() + "time(s)");
            });
    

    【讨论】:

      猜你喜欢
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 2014-05-18
      • 2021-07-02
      • 1970-01-01
      相关资源
      最近更新 更多