java中list去重:如何使用Java实现List去重

实现实现Java中list去重的方法有很多,可以根据需要选择不同的方法。介绍几种常用的方法:使用Set集合:Set集合中不允许有重复元素,因此可以将List集合中的元素添加到Set集合中,然后再将Set集合中的元素添加到新的List集合中,这样就可以实现List集合的去重。

实现

Java中list去重的方法有很多,可以根据需要选择不同的方法。介绍几种常用的方法:

1. 使用Set集合:Set集合中不允许有重复元素,因此可以将List集合中的元素添加到Set集合中,然后再将Set集合中的元素添加到新的List集合中,这样就可以实现List集合的去重。

代码实现:


java
public static List removeDuplicate(List list) {
    Set set = new HashSet();
    List newList = new ArrayList();
    for (Iterator iter = list.iterator(); iter.hasNext();) {
        Object element = iter.next();
        if (set.add(element))
            newList.add(element);
    }
    return newList;
}

2. 使用for循环:可以使用for循环,遍历List集合中的元素,如果新的List集合中不存在当前元素,则将该元素添加到新的List集合中,最终得到去重后的List集合。

代码实现:


java
public static List removeDuplicate(List list) {
    List newList = new ArrayList();
    for (Iterator iter = list.iterator(); iter.hasNext();) {
        Object element = iter.next();
        if (!newList.contains(element))
            newList.add(element);
    }
    return newList;
}

3. 使用Stream API:可以使用Stream API提供的distinct()方法,对List集合中的元素进行去重操作,最终得到去重后的List集合。

代码实现:


java
public static List removeDuplicate(List list) {
    return list.stream().distinct().collect(Collectors.toList());
}

本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处

(260)
java开发述职报告:Java开发员的业绩报告
上一篇
java timer用法:使用Java Timer实现定时任务
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(31条)