2016-11-21 61 views
1

下面的问题是,在Java中HashMap中字符串和计数数目

样本数据:https://tartarus.org/martin/PorterStemmer/output.txt

我有包含类似于上述列表中有许多重复的单词的tokenizationString字符串数组话。

我必须将该字符串数组转换为散列表,然后使用散列表来计算每个单词的使用次数(计算字符串数组中的重复值,但我必须使用散列表相关的方法)。

我想这样做

Map<Integer, String> hashMap = new HashMap<Integer, String>();  
      for(int i = 0 ; i < tokenizationString.length; i++) 
       { 
        hashMap.put(i, tokenizationString[i]); 

       } 

在那之后我将不得不时间#它们用于字符串数组排序。

最后,我希望能够打印出结果,如:

the "was used" 502 "times" 
i "was used" 50342 "times" 
apple "was used" 50 "times" 

回答

1

而不是

hashMap.put(i, tokenizationString[i]); 

第一次检查,如果这个词已经存在,并增加相应的条目:

int count = hashMap.containsKey(tokenizationString[i]) ? hashMap.get(tokenizationString[i]) : 0; 
hashMap.put(tokenizationString[i], count + 1); 
+0

嗨我已经尝试过,但代码无法正常工作。你用Java写了吗? 我改变了上面的代码到 Map hashMap = new HashMap (); 它的工作原理。所以hashmap的结构将为 String:是映射的键 Integer:是键重复的次数。 –

+0

是的,你需要保留字符串作为hashmap的关键字,并将count作为值。 –

3

首先,你的地图应该像Map<String, Integer>(字符串,其频率)。 我给你的Java 8流解决方案。

public static void main(String[] args) { 
    try (Stream<String> lines = Files.lines(Paths.get("out.txt"))) { 
     Map<String, Long> frequency = lines 
       .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) 
       .entrySet() 
       .stream() 
       .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) 
       .collect(Collectors.toMap(
         Map.Entry::getKey, 
         Map.Entry::getValue, 
         (o, n) -> o, 
         LinkedHashMap::new 
       )); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

上面的代码将逐行从文件中读取。然后收集为频率图。然后再将它们转换为entrySet流。然后根据相反的顺序对数据流进行排序。最后将它们收集为LinkedHashMapLinkedHashMap,因为它会保持insersion顺序。看看Java 8 Stream API。

0

您可以通过Google Gauva library的MultiMap类实现此功能,如下所示。在这个链接也找到工作示例 - https://gist.github.com/dkalawadia/8d06fba1c2c87dd94ab3e803dff619b0

FileInputStream fstream = null; 
    BufferedReader br = null; 
    try { 
     fstream = new FileInputStream("C:\\temp\\output.txt"); 
     br = new BufferedReader(new InputStreamReader(fstream)); 

     String strLine; 

     Multimap<String, String> multimap = ArrayListMultimap.create(); 
     // Read File Line By Line 
     while ((strLine = br.readLine()) != null) { 
      multimap.put(strLine, strLine); 
     } 

     for (String key : multimap.keySet()) { 
      System.out.println(key + "was used " + multimap.get(key).size() + "times"); 
     } 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (fstream != null) { 
      fstream.close(); 
     } 
     if(br!=null){ 
      br.close(); 
     } 
    }