简体   繁体   English

Java对String数组进行排序并返回不同的Item

[英]Java sorting a String array and return the distinct Item

I have given the two arrays 我给了两个数组

array 1 :  a, b, c, d
array 2 :  a, b, c 

I have used the 我用过

ArrayList<String> combine =  new ArrayList<String> ()

and all the elements in array 1 and array 2 以及array 1array 2所有元素

By sorting, I have found 通过排序,我发现

a , a , b , b , c , c , d 

Would you please tell me how to compare the elements in these two arrays and return the distinct items (d for example)? 您能否告诉我如何比较这两个数组中的元素并返回不同的项目(例如d)?

Something like 就像是

ArrayList<String> charsA = new ArrayList<>();
charsA.addAll(Arrays.asList("a", "a", "b", "c", "d"));
ArrayList<String> charsB = new ArrayList<>();
charsB.addAll(Arrays.asList("a", "b", "c"));

charsA.removeAll(charsB);
System.out.println(charsA);

prints 版画

[d]

Obviously use a different list if you don't want any of the two original to be affected. 如果您不希望两个原始文档中的任何一个受到影响,则可以使用不同的列表。

The removeAll(Collection) method removeAll(Collection)方法

Removes from this list all of its elements that are contained in the specified collection. 从此列表中删除指定集合中包含的所有元素。

If you want to do it with Arrays then you have to loop over both the arrays and compare values one by one. 如果要对数组进行操作,则必须遍历两个数组并逐一比较值。 If you want to do it with ArraysLists then you can build your logic around contains() and remove() methods. 如果要使用ArraysLists进行操作,则可以围绕contains()remove()方法构建逻辑。

    List<String> list1 = new ArrayList<String>();
    list1.add("a");
    list1.add("b");
    list1.add("c");
    list1.add("d");

    List<String> list2 = new ArrayList<String>();
    list2.add("a");
    list2.add("b");
    list2.add("c");

    List<String> distinctList = new ArrayList<String>();

    for (String string : list1) {
        if (!list2.contains(string)) {
            distinctList.add(string);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM