LinkedList中去除重复的元素!

要求:

         已知数组存放一批QQ号码,QQ号码最长为11位,最短为5位String[] strs ={"12345","67891","12347809933","98765432102","67891","12347809933"}。
 将该数组里面的所有qq号都存放在LinkedList中,将linkedList中重复元素删除,然后将linkedList中所有元素分别用迭代器和增强for循环打印出来。

import java.util.Iterator;
import java.util.LinkedList;

public class Demo2 {

    //排重
    public  static  LinkedList  paichong(LinkedList list){
         LinkedList linkedList=new LinkedList<>();
         Iterator it=list.iterator();
         while (it.hasNext()){
             String str=it.next();
             if (!linkedList.contains(str)){
                 linkedList.add(str);
             }
         }
        return linkedList;
    }

    public static void main(String[] args) {

        LinkedList linkedList=new LinkedList<>();
        String[] strs ={"12345","67891","12347809933","98765432102","67891","12347809933"};
        for (int i = 0; i < 6; i++) {
              linkedList.add(strs[i]);
        }
        System.out.println("集合中的元素:"+linkedList.toString());
        //排重
        LinkedList lis=paichong(linkedList);
        System.out.println("去除重复元素之后:"+lis);
        System.out.println("----------增强for------------");
        for (String s : lis) {
            System.out.println(s);
        }
        System.out.println("-------迭代器----------");
        Iterator it = lis.iterator();
        while (it.hasNext()){
            System.out.println(it.next());

        }

        }
    }

控制台输出结果:

集合中的元素:[12345, 67891, 12347809933, 98765432102, 67891, 12347809933]
去除重复元素之后:[12345, 67891, 12347809933, 98765432102]
----------增强for------------
12345
67891
12347809933
98765432102
-------迭代器----------
12345
67891
12347809933
98765432102

你可能感兴趣的:(LinkedList中去除重复的元素!)