元素出现的次数

时间:2019-07-04 16:03:21

标签: java hashmap treeset

我正在尝试使用树集和哈希图查找元素出现的次数。 当我运行程序时,哈希表中的值没有增加

我尝试了map.put(data,map.get(data)+1)导致空指针异常。

public class ReadData {
    public static void main(String[] args) {
        File f = new File("E:\\new1.txt");
        try {
            BufferedReader br = new BufferedReader(new FileReader(f));
            String data = "";
            int count =1;
            HashMap<String,Integer> map = null;
            TreeSet<String> set = new TreeSet<String>();
            set.add("");
            while((data=br.readLine())!=null) {

                 map = new HashMap<String,Integer>();
            if(set.contains(data)) {
                map.put(data,map.get(data)+1);
                System.out.println("correct");
                System.out.println(count+1);

            }else
            {
                map.put(data,count);
                set.add(data);
                System.out.println("Not correct");
            }
            //System.out.println(map);
             Set sets = map.entrySet();
              Iterator iterator = sets.iterator();
              while(iterator.hasNext()) {
                 Map.Entry mentry = (Map.Entry)iterator.next();
                System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
                 System.out.println(mentry.getValue());

              }
            }

        }catch(Exception e) {
            System.out.println(e);
        }

    }
}

输入:-橙色 苹果 橙子 橙色

o / p键为橙色,值为3 键是苹果,值是1

输出的键是:橙色,值是:1 关键是:苹果&值是:1 java.lang.NullPointerException

4 个答案:

答案 0 :(得分:3)

您可以使用Collectors.groupingBy()Collectors.counting()使用流来使其更干净。您还应该使用try-with-resource构造和新的Files类:

String delimiter = " ";
Path p = Paths.get("E:", "file.txt");
try (BufferedReader br = Files.newBufferedReader(p)) {
    Map<String, Long> result = br.lines()
            .flatMap(l -> Arrays.stream(l.split(delimiter)))
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    System.out.println(result);
}

对于orange apple orange orange输入,此代码将打印{orange=3, apple=1}

答案 1 :(得分:0)

请注意

    HashMap<String,Integer> map = null;

与空白地图不同。首先,您必须先创建一个新地图才能使用它。

以这种情况为例

        HashMap<String,Integer> map = null;

然后您要在循环中创建一个新地图,这很难按您的目的阅读。我建议将实例集与地图实例化并删除

map = new HashMap<String,Integer>();

在while循环内

您的代码应类似于

HashMap<String, Integer> map = new HashMap<String, Integer>();
            TreeSet<String> set = new TreeSet<String>();
            set.add("");
            while ((data = br.readLine()) != null) {

答案 2 :(得分:0)

您还可以使用TreeMap代替使用HashMap + TreeSet。

public class ReadData {
    public static void main(String[] args) {
        try {
            File f = new File("E:\\new1.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            TreeMap<String,Integer> map = new TreeMap(String, Integer);

            while((String data=br.readLine()) != null) {

                String[] fruitNames = data.split(" "); // or regex s+ can also be used

                for(String fruitName : fruitNames){
                    Integer count = map.get(fruitName);
                    Integer newVal = count == null ? 1 : count+1 ;
                    map.put(fruitName, newVal);
                }
                // iterate over keys in TreeMap
            }
        }catch(Exception e) {
            System.out.println(e);
        }

    }
}

答案 3 :(得分:-1)

如果要计算字符串的出现次数,则只需使用StringUtils.countMatches Apache Commons lang。

//First get all the words from your line - 
String[] allWords = data.split("\\s");

//Retrieve unique strings
        String[] uniqueStrings = Arrays.stream(allWords).distinct().toArray(String[]::new);

// Print the occurrence of each string in data
        for (String word: uniqueStrings){

               System.out.println("Count of occurrences for the word " + word + "is: " + StringUtils.countMatches(data, word));
        }