这两个类可能会有所帮助。让我知道如何进一步改进这一点。随意在您自己的工作中使用下面的代码。我必须指出,当前代码不处理重复的列表元素。
import java.util.List;
public class ListDiff<T> {
private List<T> removed;
private List<T> added;
public ListDiff(List<T> removed, List<T> added) {
super();
this.removed = removed;
this.added = added;
}
public ListDiff() {
super();
}
public List<T> getRemoved() {
return removed;
}
public List<T> getAdded() {
return added;
}
}
实用类。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ListUtil {
public static <T> ListDiff<T> diff(List<T> one, List<T> two) {
List<T> removed = new ArrayList<T>();
List<T> added = new ArrayList<T>();
for (int i = 0; i < one.size(); i++) {
T elementOne = one.get(i);
if (!two.contains(elementOne)) {
//element in one is removed from two
removed.add(elementOne);
}
}
for (int i = 0; i < two.size(); i++) {
T elementTwo = two.get(i);
if (!one.contains(elementTwo)) {
//element in two is added.
added.add(elementTwo);
}
}
return new ListDiff<T>(removed, added);
}
public static <T> ListDiff<T> diff(List<T> one, List<T> two, Comparator<T> comparator) {
List<T> removed = new ArrayList<T>();
List<T> added = new ArrayList<T>();
for (int i = 0; i < one.size(); i++) {
T elementOne = one.get(i);
boolean found = false;
//loop checks if element in one is found in two.
for (int j = 0; j < two.size(); j++) {
T elementTwo = two.get(j);
if (comparator.compare(elementOne, elementTwo) == 0) {
found = true;
break;
}
}
if (found == false) {
//element is not found in list two. it is removed.
removed.add(elementOne);
}
}
for (int i = 0; i < two.size(); i++) {
T elementTwo = two.get(i);
boolean found = false;
//loop checks if element in two is found in one.
for (int j = 0; j < one.size(); j++) {
T elementOne = one.get(j);
if (comparator.compare(elementTwo, elementOne) == 0) {
found = true;
break;
}
}
if (found == false) {
//it means element has been added to list two.
added.add(elementTwo);
}
}
return new ListDiff<T>(removed, added);
}
public static void main(String args[]) {
String[] arr1 = { "london", "newyork", "delhi", "singapore", "tokyo", "amsterdam" };
String[] arr2 = { "london", "newyork", "delhi", "singapore", "seoul", "bangalore", "oslo" };
ListDiff<String> ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2));
System.out.println(ld.getRemoved());
System.out.println(ld.getAdded());
ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2), new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}); //sample for using custom comparator
System.out.println(ld.getRemoved());
System.out.println(ld.getAdded());
}
}