我设计了两种方案
第一种只显示第几行重复了,并没有说明第几行和第几行重复,实现方式比较简单
public static <T> String checkListRepeat(List<T> list) {
if (CollectionUtils.isEmpty(list)) {
return "数据为空!";
} else {
int errorCount = 0;
StringBuilder errorInfo = new StringBuilder();
//校验Excel中是否有重复的
HashSet<T> ts = new HashSet<>();
for (int i = 0; i < list.size(); i++) {
T t = list.get(i);
if (!ts.add(t)) {
errorCount++;
errorInfo.append("第").append(i + 2).append("行有重复,请核实;");
}
if (errorCount == 10) {
return errorInfo.toString();
}
}
if (errorCount != 0) {
return errorInfo.toString();
}
}
return null;
}
第二种可以显示第几行与第几行重复了,实现方式比较复杂
public static <T> String checkListRepeatAll(List<T> list) {
if (CollectionUtils.isEmpty(list)) {
return "数据为空!";
} else {
int mapCapacity = (int) (list.size() / 0.75) + 1;
//校验Excel中是否有重复的,Integer为行数
Map<T, Integer> checkMap = new HashMap<>(mapCapacity);
//最终存入的重复行数
Map<T, Set<Integer>> repeatMap = new HashMap<>(mapCapacity / 4);
for (int i = 0; i < list.size(); i++) {
int row = i + 2;
T pojo = list.get(i);
//将值和行数放入Map,value为原先重复行存入的数据
Integer value = checkMap.put(pojo, row);
//当前的值已经存在Map中
if (value != null) {
Set<Integer> repeatValue = repeatMap.get(pojo);
//如果是第一次重复的,则为null,需要将第一个重复的值存入Map中
if (repeatValue == null) {
repeatValue = new HashSet<>();
repeatValue.add(value);
}
//将当前的行数也存入Map
repeatValue.add(row);
repeatMap.put(pojo, repeatValue);
}
}
if (!repeatMap.isEmpty()) {
//有重复行
StringBuilder errorInfo = new StringBuilder();
for (Map.Entry<T, Set<Integer>> tSetEntry : repeatMap.entrySet()) {
Set<Integer> value = tSetEntry.getValue();
for (Integer integer : value) {
errorInfo.append(integer).append("行、");
}
errorInfo.deleteCharAt(errorInfo.lastIndexOf("、")).append("重复;");
}
errorInfo.append("请核实!");
return errorInfo.toString();
}
}
return null;
}