繁体   English   中英

在Java中将ArrayList转换为Hashset

[英]Converting ArrayList to Hashset in java

我有这段代码可以读取并计算txt文件中的每个单词,但是我只希望它对一行中的每个单词进行一次计数,因此我试图创建一个HashSet,但是我无法将ArrayList转换为HashSet的。 这是我的代码:

try {
    List<String> list = new ArrayList<String>();
    int totalWords = 0;
    int uniqueWords = 0;
    File fr = new File("filename.txt");
    Scanner sc = new Scanner(fr);
    while (sc.hasNext()) {
        String words = sc.next();
        String[] space = words.split(" ");
        Set<String> set = new HashSet<String>(Arrays.asList(space));
        for (int i = 0; i < set.length; i++) {
            list.add(set[i]);
        }
        totalWords++;
    }
    System.out.println("Words with their frequency..");
    Set<String> uniqueSet = new HashSet<String>(list);
    for (String word : uniqueSet) {
        System.out.println(word + ": " + Collections.frequency(list,word));
    }
} catch (Exception e) {

    System.out.println("File not found");

  }  

如果有人可以帮助您解释为什么长度“无法解析或不是字段”,以及为什么我对“ set [i]”有错误,告诉我必须将其解析为字符串。 谢谢

正如在注释中告诉您的那样,您不能使用[]length因为任何Set都是Collection而不是数组:

您可以这样尝试:

try {
    List<String> list = new ArrayList<String>();
    int totalWords = 0;
    int uniqueWords = 0;
    File fr = new File("filename.txt");
    Scanner sc = new Scanner(fr);
    while (sc.hasNext()) {
         String words = sc.next();
         String[] space = words.split(" ");
         Set<String> set = new HashSet<String>(Arrays.asList(space));
         for(String element : set){
              list.add(element);
         }
         totalWords++;
    }
    System.out.println("Words with their frequency..");
    Set<String> uniqueSet = new HashSet<String>(list);
    for (String word : uniqueSet) {
         System.out.println(word + ": " + Collections.frequency(list,word));
    }
} catch (Exception e) {
    System.out.println("File not found");
} 

我已经使用了地图数据结构来存储和更新单词及其各自的频率。

根据您的要求:即使每个单词在同一行中多次出现,每个单词也应仅计数一次

遍历每一行:

 Store all the words in the set.

 Now just iterate over this set and update the map data structure.

因此,最后对应于映射中的单词的值将是所需的频率。

您可以在下面查看我的代码:

import java.io.File;
import java.util.*;

public class sol {
    public static void main(String args[]) {
        try {
            File fr = new File("file.txt");
            Scanner sc = new Scanner(fr);

            // to maintain frequency of each word after reading each line..
            HashMap<String, Integer> word_frequency = new HashMap<String, Integer>();

            while(sc.hasNextLine()) {
                // input the line..
                String line = sc.nextLine();
                String words[] = line.split(" ");

                // just store which unique words are there in this line..
                HashSet<String> unique_words = new HashSet<String>();

                for(int i=0;i<words.length;i++) {
                    unique_words.add(words[i]);     // add it to set..
                }

                // Iterate on the set now to update the frequency..
                Iterator itr = unique_words.iterator();

                while(itr.hasNext()) {
                    String word = (String)itr.next();   

                    // If this word is already there then just increment it..
                    if(word_frequency.containsKey(word)) {
                        int old_frequency = word_frequency.get(word);
                        int new_frequency = old_frequency + 1;
                        word_frequency.put(word, new_frequency);
                    }
                    else {
                        // If this word is not there then put this 
                        // new word in the map with frequency 1..

                        word_frequency.put(word, 1);
                    }
                }
            }

            // Now, you have all the words with their respective frequencies..
            // Just print the words and their frequencies..
            for(Map.Entry obj : word_frequency.entrySet()) {
                String word = (String)obj.getKey();
                int frequency = (Integer)obj.getValue();

                System.out.println(word+": "+frequency);
            }
        }
        catch(Exception e) {
            // throw whatever exception you wish.. 
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM