如何从对象列表中删除重复项

时间:2015-10-21 05:58:02

标签: java duplicates

我有一个带有以下数据的excel文件(虚拟)

a   b   c
d   b   c
e   b   c
f   b   c
g   b   c
e   b   c
d   b   c
d   b   c
d   b   c

我正在读取此文件并将结果存储在Set中,以便可以删除重复项,并且我只获得唯一列表。 以下是我试过的内容

FileInputStream file = new FileInputStream(new File("C:\\Users\\harshita.sethi\\Desktop\\ALLOT010T_Input_Keywords.xls"));
HSSFWorkbook w = new HSSFWorkbook(file);
HSSFSheet sheet = w.getSheetAt(0);
int totalrows = sheet.getLastRowNum();

System.out.println(sheet.getRow(0).getPhysicalNumberOfCells());
String[][] data = new String[totalrows+1][sheet.getRow(0).getPhysicalNumberOfCells()];
Set<String[]> keySet = new HashSet<>();
for (int i = 0; i <= totalrows; i++) {
    for (int j = 0; j < sheet.getRow(0).getPhysicalNumberOfCells(); j++) {
        HSSFCell cell = sheet.getRow(i).getCell(j);
        // writing keywords from excel into a hashmap

        data[i][j]=cell.getRichStringCellValue().getString();
    }
    keySet.add(data[i]);

}
Iterator<String[]> iterator = keySet.iterator();
System.out.println("Output Set is as below");
while(iterator.hasNext()){
    String[] next = iterator.next();
    System.out.println(next[0] + "\t"+ next[1] +"\t "+next[2]);
}

此代码的输出如下所示

Output Set is as below
d   b    c
e   b    c
a   b    c
d   b    c
d   b    c
g   b    c
e   b    c
f   b    c
d   b    c

该集合未删除副本。我可以用什么其他方法来消除这些重复。 任何列都可以具有不同或相同的值。因此,我无法根据特定列删除重复项。

我希望整行都是唯一的。

PS:这个数据真是太愚蠢了。在实际场景中,我有更多列,任何列值都可以不同,这将使行唯一。

2 个答案:

答案 0 :(得分:3)

<body class="beforepace"> <div id="golden" onmouseover="showdesc('golden-desc','golden');" onmouseout="hidedesc('golden-desc','golden');"> <div id="golden-desc" class="desc">Golden</div> </div> <div id="utopia" onmouseover="showdesc('utopia-desc','utopia');" onmouseout="hidedesc('utopia-desc','utopia');"> <div id="utopia-desc" class="desc">Utopia</div> </div> <div id="logo" class="default">logo here</div> </body>无法使用Set<String[]>实现,因为数组不会覆盖HashSet类的默认hashCode()equals()实现。< / p>

您的替代方案是使用Object(即将每个Set<List<String>>转换为String[],这可以通过List<String>)或Arrays.asList()轻松完成自定义TreeSet<String[]>

例如:

Comparator<String[]>

答案 1 :(得分:2)

您可以使用比较器类:

您可以将TreeSet与自定义Comparator一起使用,以比较String数组的相等性。

Set<String[]> mySet = new TreeSet<>(new Comparator<String[]>() {

  @Override
  public int compare(String[] o1, String[] o2) {
    //logic for comparison.
  }

});

另一种更好的方法是使用集合。使用List而不是String []:

例如:

Set<List<String>> set = //...
set.add(Arrays.asList("a", "b", "c"));
set.add(Arrays.asList("a", "b", "c"));
set.add(Arrays.asList("a", "b", "d"));

System.out.println(set.size()); // 2