首页 > 其他分享 >一个数组中的元素在另一个数组中存在,就移除

一个数组中的元素在另一个数组中存在,就移除

时间:2022-11-09 10:11:21浏览次数:46  
标签:String newArr 元素 System length 数组 移除 new

提供两种解决办法

方案一

// 两个数组,一个数组a中的元素在另一个数组b中存在,就把A中的这个元素移除,得到新的数组
    public static String[] getNewArrByTwoArr(String[] targetArr,String[] sourceArr){
        List<String> newList = new LinkedList<>();
        List<String> sourceList = Arrays.asList(sourceArr);
        for (String target : targetArr) {
            if(!sourceList.contains(target)){
                newList.add(target);
            }
        }
        return newList.toArray(new String[newList.size()]);
    }

    public static void main(String[] args) {
        String[] a = new String[]{"dd","ww","cc"};
        String[] b = new String[]{"aa","bb","cc"};
        String[] newArr = getNewArrByTwoArr(a,b);
        System.out.println("newArr.length:" + newArr.length);
        for (String s : newArr) {
            System.out.println("s:" + s);
        }
    }

方案二

// 两个数组,一个数组a中的元素在另一个数组b中存在,就把A中的这个元素移除,得到新的数组
    public static String[] getNewDistinctArrByTwoArr(String[] targetArr,String[] sourceArr){
        List<String> targetList = new ArrayList(Arrays.asList(targetArr));
        List<String> sourceList = new ArrayList(Arrays.asList(sourceArr));
        targetList.removeAll(sourceList);
        return targetList.toArray(new String[targetList.size()]);
    }

    public static void main(String[] args) {
        String[] a = new String[]{"dd","ww","cc"};
        String[] b = new String[]{"aa","bb","cc"};
        String[] newArr = getNewArrByTwoArr(a,b);
        String[] newArr2 = getNewDistinctArrByTwoArr(a,b);
        System.out.println("newArr.length:" + newArr.length);
        for (String s : newArr) {
            System.out.println("s:" + s);
        }
        System.out.println("newArr.length:" + newArr2.length);
        for (String s : newArr2) {
            System.out.println("s:" + s);
        }
    }

 

标签:String,newArr,元素,System,length,数组,移除,new
From: https://www.cnblogs.com/zhangliang88/p/16872638.html

相关文章