比较两个数组列表 [英] Compare two arraylist
本文介绍了比较两个数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个的ArrayList
I have two Arraylists:
ArrayList a1 = new ArrayList();
a1.add("5");
a1.add("10");
a1.add("20");
a1.add("50");
a1.add("100");
a1.add("500");
a1.add("1000");
ArrayList a2 = new ArrayList();
a2.add("50");
a2.add("500");
a2.add("1000");
我如何比较这两的ArrayList和1,如果A2在A1存在,0,如果不存在加入到新的ArrayList(A3),所以结果将在下面为ArrayList的A3?
How can I compare this two arraylists and add into new arraylist(a3) with 1 if a2 exist in a1 and 0 if not exist, so the result will below for arraylist a3?
a3[0] = 0
a3[1] = 0
a3[2] = 0
a3[3] = 1
a3[4] = 0
a3[5] = 1
a3[6] = 1
在此先感谢
推荐答案
首先,我会建议你使用泛型 。其次,对于 A2
可能是一个的 设置
代替。第三点,你可能希望从字符串
到整数
(因为它们都是整数)。
First, I would advice you to use generics. And secondly, for a2
could be a Set
instead. And thirdly you might want to change from String
to Integer
(since they are all integers).
但对于你的例子,这是一个办法做到这一点:
But for your example this is a way to do it:
ArrayList<Integer> a3 = new ArrayList<Integer>();
for (String a : a1)
a3.add(a2.contains(a) ? 1 : 0);
完整的示例(以 HashSet的
和整数
键入):
public static void main(String... args) {
List<Integer> a1 = Arrays.asList(5, 10, 20, 50, 100, 500, 1000);
Set<Integer> a2 = new HashSet<Integer>(Arrays.asList(50, 500, 1000));
ArrayList<Integer> a3 = new ArrayList<Integer>();
for (Integer a : a1)
a3.add(a2.contains(a) ? 1 : 0);
System.out.println(a3);
}
输出:
[0, 0, 0, 1, 0, 1, 1]
这篇关于比较两个数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文