我有多个字符串的2D数组,有点像这样
Array 1
[0] = ["01/01/01","Bill","17","0.86"]
[1] = ["02/01/01","Bill","12","0.84"]
[2] = ["03/01/01","Bill","15","0.85"]
Array 2
[0] = ["01/01/01","Joe","14","0.81"]
[1] = ["02/01/01","Joe","15","0.83"]
[2] = ["04/01/01","Joe","19","0.85"]
我正在尝试仅比较同一天的数据,所以我需要做的是搜索两个数组中的日期,而不是另一个,然后删除它们。所以在上面的例子中,我将从两个数组中删除[2]。有没有办法使用List / Collection retainAll执行此操作,还是必须编写循环?哦,我正在使用Java。
答案 0 :(得分:0)
没有使用集合删除项目的直接方法。但是如果两个数组都按日期排序,那么您将能够比较数据而不从每个数组中删除缺少的日期。
答案 1 :(得分:0)
好吧,我不喜欢使用数组来解决这个问题。从数组中删除元素是一个坏主意。您可以尝试链接列表。像这样的东西
for (int i=0; i < array1List.size(); i++) {
String date = array1List.get(i)[0];
int index = -1;
for(int j=0; j < array2List.size(); j++) {
if array2List.get(j)[0].equals(date)) {
index = j;
break;
}
if(index >= 0) array2List.remove(j);
}
}
答案 2 :(得分:0)
要使用Collection
执行此操作,您必须将每个数组条目放入一个对象中。类似的东西:
class DayInfo {
String date;
String name;
...
public DayInfo(String[] arrayData) {
this.date = arrayData[0];
this.name = arrayData[1];
...
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof DayInfo))
return false;
if (date == null) {
return ((DayInfo)obj).date == null;
} else {
return date.equals((DayInfo)obj).date);
}
}
@Override
public int hashCode() {
if (date == null)
return 0;
else
return date.hashCode();
}
}
然后,如果您将两个数组加载到DateInfo
集合中:
Set<DayInfo> dayInfos1 = new HashSet<DayInfo>(array1.length);
for (String[] arrayEntry : array1)
dayInfos1.add(new DayInfo(arrayEntry));
Set<DayInfo> dayInfos2 = new HashSet<DayInfo>(array2.length);
for (String[] arrayEntry : array2)
dayInfos2.add(new DayInfo(arrayEntry));
现在您可以在两个方向上使用retainAll
:
// remove everything from set #1 that doesn't have a date in set #2
dayInfos1.retainAll(dayInfos2);
// remove everything from set #2 that doesn't have a date in set #1
dayInfos2.retainAll(dayInfos1);
我认为这样可行。