zoukankan      html  css  js  c++  java
  • 找出现有Vector或ArrayList或数组中重复的元素&给现有Vector或ArrayList或数组去重

    //直接上代码:
    public static void main(String[] args) { List<Integer> list = new Vector<Integer>(20); for (int i = 0; i < 10; i++) { list.add(i % 3); list.add(i % 6); list.add(i % 2); list.add(i % 4); } System.out.println("原始元素:" + list); List<Integer> reList = new Vector<Integer>(20); for (int i = 0; i < list.size() - 1; i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(i) == list.get(j)) { reList.add(list.remove(i)); i--; break; } } } // System.out.println("去重后:" + list); // System.out.println("重复元素:" + reList); // 输出: // 原始元素:原始元素:[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 0, 2, 0, 3, 1, 3, 1, 4, 0, 0, 2, 5, 1, 1, 0, 0, 0, 2, 1, 1, 1, 3, 2, 2, 0, 0, 0, 3, 1, 1] // 去重后:[4, 5, 2, 0, 3, 1] // 重复元素:[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 0, 2, 0, 3, 1, 3, 1, 0, 0, 2, 1, 1, 0, 0, 0, 2, 1, 1, 1, 3, 2, 0, 0, 1] //去重方法2 Set<Integer> intset = new HashSet<Integer>(list); System.out.println("set去重后" + intset); // 输出: // 原始元素:[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 0, 2, 0, 3, 1, 3, 1, 4, 0, 0, 2, 5, 1, 1, 0, 0, 0, 2, 1, 1, 1, 3, 2, 2, 0, 0, 0, 3, 1, 1] // set去重后[0, 1, 2, 3, 4, 5] //数组 List<Integer> notReList = new Vector<Integer>(20); int[] intarr = new int[]{1, 2, 4, 5, 6, 3, 4, 2, 3, 4, 34, 5, 23, 5, 2, 3, 4, 3, 3,99}; for (int i = 0; i < intarr.length ; i++) {//如果不计算notReList用i < intarr.length改成i < intarr.length-1 if (!notReList.contains(intarr[i])) { notReList.add(intarr[i]); } for (int j = i + 1; j < intarr.length; j++) { if (intarr[i] == intarr[j]) { reList.add(intarr[i]); break; } } } System.out.println("去重后:" + notReList); System.out.println("重复元素:" + reList); // 输出: // 去重后:[1, 2, 4, 5, 6, 3, 34, 23, 99] // 重复元素:[2, 4, 5, 3, 4, 2, 3, 4, 5, 3, 3]

    // list和数组也可以互转:
    // List intList=Arrays.asList(intarr);或
    // Integer[] intarr2=new Integer[list.size()];
    // list.toArray(intarr2);

    }

    版权所有,转载请注明出处:http://www.cnblogs.com/langtianya/p/4676816.html 

  • 相关阅读:
    (转)【web前端培训之前后端的配合(中)】继续昨日的故事
    ural(Timus) 1136. Parliament
    scau Josephus Problem
    ACMICPC Live Archive 6204 Poker End Games
    uva 10391 Compound Words
    ACMICPC Live Archive 3222 Joke with Turtles
    uva 10132 File Fragmentation
    uva 270 Lining Up
    【转】各种字符串哈希函数比较
    uva 10905 Children's Game
  • 原文地址:https://www.cnblogs.com/langtianya/p/4676816.html
Copyright © 2011-2022 走看看