-1

i've been stuck for hours now and can't find a solution. I want to compare two ArrayLists where i want to put each unique element from one of the list into another arrayList.

For example, if my one arrayList contain {0,1,2,3} and i want to compare it to {{1},{2},{3}} i want to recieve {2} in my 'unqiue' arraylist please help me

AFTER EDIT

I will be more specific. ArrayList1={0,1,2,3,4} and ArrayList2={{0, 1} {0,1,2}} So what i want is to have the only unique from ArrayList1 in a single ArrayList. in this example i want ArrayList3= {3,4}

4

2 回答 2

0

如果我正确解释了您的问题,您想在 2 个列表中形成一个新的常见元素列表吗?如果是这样,遍历列表之一并检查第二个是否列出contains(Object)了该元素,如果是,则将其添加到第三个列表中。我目前无法提供代码示例,但是当我使用计算机时,我会很高兴编辑它(如有必要)。

编辑:

代码可能看起来像这样:

    private static <T> List<T> getUniqueList(final List<T> first, final List<T> second){
    final List<T> unique = new ArrayList<T>();
    for(final T element : first)
        if(second.contains(element))
            unique.add(element);
    return unique;
}

或者,如果您使用的是 Java 8:

    private static <T> List<T> getUniqueList(final List<T> first, final List<T> second){
    final List<T> unique = new ArrayList<>();
    first.stream().filter(second::contains).forEach(unique::add);
    return unique;
}
于 2013-08-14T12:10:56.150 回答
0

您可以使用方法boolean removeAll(Collection c) of List

它将从此列表中删除指定集合中包含的所有元素。因此,在调用它之后,您的列表将包含独特的元素。

假设你有arrayList1并且arrayList2你可以像这样比较它们:

arrayList1.removeAll(arrayList2);

现在arrayList1只包含独特的元素。

于 2013-08-14T11:55:57.643 回答