字符串数组(String []) 去掉重复值的方法

时间:2021-08-19 17:05:38
public class Demo {
    /**
     * 去掉重复值
     */
    public static void main(String[] args) {
        String test = "100,120,166,1555,120,150,100";
        String[] test1 = test.split(",");
        ArrayList list = new ArrayList();
        for (int i = 0; i < test1.length; i++) {
            if (!list.contains(test1[i]))
                list.add(test1[i]);
        }
        for (int i = 0; i < list.size(); i++)
            System.out.println(list.get(i));
    }
}

这个方法是很好,但是还有更加简单的

public class Demo {
    /**
     * 去掉重复值
     */
    public static void main(String[] args) {
        String test = "100,120,166,1555,120,150,100";
        String[] test1 = test.split(",");
        List list = Arrays.asList(test1);
        Set set = new HashSet(list);
        String [] rid=(String [])set.toArray(new String[0]);
        for (int i = 0; i < rid.length; i++) {
            System.out.println(rid[i]);
        }
    }
}