java 獲取兩個list集合裡面中不相同的元素
阿新 • • 發佈:2019-02-14
在專案開發中,經常會對比不同的集合,獲取裡面不相同的元素,一般會用到好幾種方法,這裡算是一種,mark一下。
public static List<Integer> getDiffrent(List<Integer> list1, List<Integer> list2) {
long st = System.nanoTime();
List<String> diff = new ArrayList<String>();
List<Integer> dif = new ArrayList< Integer>();
List<String> l1=new ArrayList<>();
List<String> l2=new ArrayList<>();
for (int i = 0; i < list1.size(); i++) {
l1.add(list1.get(i)+"");
}
for (int i = 0; i < list2.size(); i++) {
l2.add(list2.get(i)+ "");
}
List<String> maxList = l1;
List<String> minList = l2;
if(list2.size()>list1.size())
{
maxList = l2;
minList = l1;
}
Map<String,Integer> map = new HashMap<String,Integer>(maxList.size());
for (String string : maxList) {
map.put(string, 1);
}
for (String string : minList) {
if(map.get(string)!=null)
{
map.put(string, 2);
continue;
}
diff.add(string);
}
for(Map.Entry<String, Integer> entry:map.entrySet())
{
if(entry.getValue()==1)
{
diff.add(entry.getKey());
}
}
for (int i = 0; i < diff.size(); i++) {
BigDecimal bd = new BigDecimal(diff.get(i));
dif.add(Integer.valueOf(bd.toPlainString()));
}
return dif;
}