您可以使用String
的Map
到您的對象類型(我使用Obj
爲了創建一個SSCCE)。
假設我們給出的清單objects
和清單strings
。
步驟:
- 把所有
objects
在map
他們str
變量作爲關鍵
- 獲取所有這些
str
變量使用map.keySet()
- 獲得了在
objects
的所有字符串,但不是在strings
由keys.removeAll(strings)
- 獲取
strings
中的所有字符串,但不包含objects
的strings.removeAll(keys)
- 獲取對應於剩餘
keys
請注意,您需要在步驟3和4小心了,因爲你需要備份的收藏品之一的objects
。
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
new Test();
}
public Test() {
List<Obj> objects = new ArrayList<>();
objects.add(new Obj("a"));
objects.add(new Obj("b"));
objects.add(new Obj("c"));
List<String> strings = new ArrayList<>();
strings.add("a");
strings.add("d");
strings.add("e");
remove(objects, strings);
System.out.println(objects);
System.out.println(strings);
}
public void remove(List<Obj> objects, List<String> strings) {
Map<String, Obj> map = new HashMap<>();
for (Obj object : objects) {
map.put(object.str, object);
}
Set<String> keys = map.keySet();
List<String> oldStrings = new ArrayList<>(strings);
strings.removeAll(keys);
keys.removeAll(oldStrings);
objects.clear();
for (String key: keys) {
objects.add(map.get(key));
}
}
public class Obj {
public String str;
public Obj(String str) {
this.str = str;
}
@Override
public String toString() {
return str;
}
}
}
打印:
[b, c]
[d, e]
你到目前爲止嘗試過什麼?給我們看一看 。 – 2013-04-11 12:58:16
如何使用Set而不是List? – Egor 2013-04-11 12:58:43
@Achintya Jain okkk只是等待 – 2013-04-11 12:58:52