【问题标题】:Java HashMap check if existing in fileJava HashMap 检查文件中是否存在
【发布时间】:2015-06-23 23:37:55
【问题描述】:

HashMap的Keys如何与String比较?

我有一个包含 100k 行的文本文件并将其放入 HashMap。

例如,我的 HashMap 如下所示:

{test1=1}
{test2=2}
up to...
{test100000=100000}

另一方面,我正在读取 100 万行的文本文件。 文本文件有这样的数据:

test1,first,input1
test2,second,input2
up to..
test1000000,1million,input1million

我用“,”将它分成一行,我只是得到该行的第一个数据。例如“测试词”:

test1
test2

所以我想做的是,我想检查我的 HashMap 的键是否存在于文本文件中。

我的问题是,我的其他文本文件比 HashMap 的行大,所以它可能会抛出 NullPointerException 或 NoSuchElement。

这是我的代码:

public static void main(String[] args) {
        File small = new File("C:\test\\testfolder\\small.txt"); // text file (100k+lines) put in hashmap
        File large = new File("C:\test\\testfolder\\big.txt"); // text file (1million+ lines) just read

        ArrayList<String> smallData= new ArrayList();
        smallData.addAll(getData(small));

        Map<String,String> smallMap = new HashMap();
        smallMap = MapSmallFile(smallData);

    try{
            LineIterator it = FileUtils.lineIterator(large,"UTF-8");
            String line;
        String[] large_data;

        while(it.hasNext()){
                line = it.nextLine();
                large_data = StringUtils.split(line, (","));



        //do the comparing here
             if(large_data[0].equalsIgnoreCase(?????)


            }
    }
    catch(Exception ex){
    ex.printStackTrace();
    }
}

private static ArrayList<String> getData(File file) {
        ArrayList<String> data = new ArrayList();
        String line;
          try{
            LineIterator it = FileUtils.lineIterator(file,"UTF-8");
                while(it.hasNext()){
                    line = it.nextLine();
                    data.add(line);     
             }
                it.close();
          }
                      catch(Exception e){
             e.printStackTrace();
          }
      return data;
    }

private static Map<String,String> MapSmallFile(ArrayList<String> inputlist){
       String[] data;
       Map<String,String> hashmap = new HashMap<String,String>();
       for(int i=0; i<inputlist.size(); i++){
           data = inputlist.get(i).split(",");
           hashmap.put(data[0], data[1]);
       }
       return hashmap;
    }

【问题讨论】:

  • Hash map get方法在key不存在时不抛出异常,返回值为null。
  • 但问题是,我如何检查密钥是否存在于行中?
  • @tutuyokgaming 你可以使用HashMap.keySet(),它返回一个List&lt;K&gt;,并使用List.contains来检查。
  • @M.Shaw 但按照这种逻辑,我只是​​在检查列表中的数据是否与行中的数据相同。但我想要的是比较 的列表是否存在于行数据中。

标签: java iterator hashmap


【解决方案1】:

我不确定这是否适合您,但如果您使用 Java 8,代码和依赖项的数量可能会大大减少。

此外,如果您想进行不区分大小写的比较,则可能值得考虑在键上调用toLowerCase(),然后再在地图中插入/搜索。

以下是一些您可以使用的可能的 Java 8 代码:

  public static void main(String[] args)
  {
    // text file (100k+lines) put in hashmap
    Path small = Paths.get("C:\\test\\testfolder\\small.txt");
    // text file (1million+ lines) just read
    Path large = Paths.get("C:\\test\\testfolder\\big.txt");

    try
    {
      Map<String, String> smallMap = Files.lines(small, StandardCharsets.UTF_8)
          .map(s -> s.split(","))
          .collect(Collectors.toMap(ss -> ss[0].toLowerCase(), ss -> ss[1]));

      Files.lines(large, StandardCharsets.UTF_8)
          .map(s -> s.split(",")[0].toLowerCase())
          .filter(s -> smallMap.containsKey(s))
          .forEachOrdered(s -> processData(s, smallMap.get(s)));
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

  private static void processData(String key, String value)
  {
    // Do what needs to be done with the matching key/value
  }

【讨论】:

    【解决方案2】:

    使用 HashMap 的 boolean containsKey(Object key) 方法似乎更好,而不是在 main() 中直接调用 equalsIgnore..()。 如有必要,您可以创建自己的类实现接口 Map,并将其作为其 HashMap 类型字段的委托者,用于自定义管理键比较。(您可以覆盖键的 equals() 和 hashCode()。第 8 项和第 9 项Josh Bloch 在 Effective Java 第 2 版中将为您提供详细指南。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-17
      • 2016-03-19
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多