简体   繁体   English

Java如何从ArrayList中删除重复项

[英]Java how to remove duplicates from ArrayList

I have a CSV file which contains rules and ruleversions. 我有一个CSV文件,其中包含规则和规则转换。 The CSV file looks like this: CSV文件如下所示:

CSV FILE:
          #RULENAME, RULEVERSION
          RULE,01-02-01
          RULE,01-02-02
          RULE,01-02-34
          OTHER_RULE,01-02-04
          THIRDRULE, 01-02-04
          THIRDRULE, 01-02-04

As you can see, 1 rule can have 1 or more rule versions. 如您所见,1个规则可以包含1个或更多规则版本。 What I need to do is read this CSV file and put them in an array. 我需要做的是读取这个CSV文件并将它们放在一个数组中。 I am currently doing that with the following script: 我目前正在使用以下脚本执行此操作:

 private static List<String[]> getRulesFromFile() {
         String csvFile = "rulesets.csv";
         BufferedReader br = null;
         String line = "";
         String delimiter = ",";

         List<String[]> input = new ArrayList<String[]>();

         try {
                br = new BufferedReader(new FileReader(csvFile));
                while ((line = br.readLine()) != null) {
                       if (!line.startsWith("#")) {
                              String[] rulesetEntry = line.split(delimiter);
                              input.add(rulesetEntry);
                       }
                }

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

But I need to adapt the script so that it saves the information in the following format: 但我需要调整脚本,以便以下列格式保存信息:

ARRAY (
          => RULE       => 01-02-01, 01-02-02, 01-02-04
          => OTHER_RULE => 01-02-34
          => THIRDRULE  => 01-02-01, 01-02-02
          )

What is the best way to do this? 做这个的最好方式是什么? Multidimensional array? 多维数组? And how do I make sure it doesn't save the rulename more than once? 我怎样才能确保它不会多次保存rulename?

You should use a different data structure, for example an HashMap, like this. 您应该使用不同的数据结构,例如HashMap,就像这样。

    HashMap<String, List<String>> myMap = new HashMap<>();

    try {
        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {
            if (!line.startsWith("#")) {
                String[] parts = string.split(delimiter);
                String key     = parts[0];
                String value   = parts[1];
                if (myMap.containsKey(key)) {
                    myMap.get(key).add(value);
                } else {
                    List<String> values = new ArrayList<String>();
                    values.add(value);
                    myMap.put(key, values);
                }
            }
        }

This should work! 这应该工作!

See using an ArrayList is not a good data structure of choice here. 在这里看到使用ArrayList不是一个好的数据结构。

I would personally suggest you to use a HashMap> for this particular purpose. 我个人建议你为这个特殊目的使用HashMap>

The rules will be your keys and rule versions will be your values which will be a list of strings. 规则将是您的密钥 ,规则版本将是您的 ,这将是一个字符串列表。

While traversing your original file, just check if the rule (key) is present, then add the value to the list of rule versions (values) already present, otherwise add a new key and add the value to it. 遍历原始文件时,只需检查规则(密钥)是否存在,然后将值添加到已存在的规则版本(值)列表中,否则添加新密钥并将值添加到其中。

For instance like this: 比如这样:

public List<String> removeDuplicates(List<String> myList) {
    Hashtable<String, String> hashtable=new Hashtable<String, String>();
    for(String s:myList) {
        hashtable.put(s, s);
    }
    return new ArrayList<String>(hashtable.values());
}

This is exactly what key - value pairs can be used for. 这正是key - value对可用于的对象。 Just take a look at the Map Interface . 只需看一下Map Interface There you can define a unique key containing various elements as value, perfectly for your issue. 在那里,您可以定义一个包含各种元素作为值的唯一键,完美地解决您的问题。

Code: 码:

// This collection will take String type as a Key 
// and Prevent duplicates in its associated values

Map<String, HashSet<String>> map = new HashMap<String,HashSet<String>>();

// Check if collection contains the Key you are about to enter
// !REPLACE! -> "rule"  with the Key you want to enter into your collection
// !REPLACE! -> "whatever" with the Value you want to associate with the key

if(!map.containsKey("rule")){
map.put("rule", new HashSet<String>());
}
else{
map.get("rule").add("whatever");
}

Reference: 参考:

Set
Map 地图

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

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