删除java arraylist中的重复项 [英] delete duplicates in java arraylist

查看:28
本文介绍了删除java arraylist中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谢谢马可.我重写了代码.尽量让它简单.这次真的可以编译了.但它只能删除彼此相邻的重复项目.例如,如果我输入 1 2 3 3 4 4 5 1 - 输出是 1 2 3 4 5 1.它最终无法提取重复项.(顺便说一句:这个网站的新手,如果有任何显示混乱我很抱歉)

Thanks Marko. I rewrite the code. try to make it simple. this time it can really compile. but it can only delete duplicate items sit next to each other. for example, if i put in 1 2 3 3 4 4 5 1 -- the output is 1 2 3 4 5 1. it can't pick up the duplicate at the end. (BTW: new to this website, if make any display mess my apologies)

这是新代码:

import java.util.*;

public class SetListDemo{
public static void main(String[] args){
    SetListType newList = new SetListType();
    Scanner keyboard = new Scanner(System.in);

    System.out.println( "Enter a series of items: ");
        String input = keyboard.nextLine();

    String[] original = input.split(" ");
    for (String s : original)
    newList.insert(s);

    List<String> finalList = new ArrayList(Arrays.asList(original)) ;

    Iterator<String> setIterator = finalList.iterator();  

    String position = null;

    while(setIterator.hasNext()){
        String secondItem = setIterator.next();

        if(secondItem.equals(position)){
            setIterator.remove();
        }   

        position = secondItem;
    }

    System.out.println("\nHere is the set list:");
    displayList(finalList);
    System.out.println("\n");
}

public static void displayList(List list){
    for(int index = 0; index <list.size(); index++)
    System.out.print(list.get(index) + ", ");
}

}

推荐答案

回答在java arraylist中删除重复项"的问题:

To answer the question "delete duplicates in java arraylist":

只需将所有元素放入 Set 中即可.

Just put all elements into a Set and you're done.

-或-

迭代您的 original 列表并将元素添加到 List,但在添加它们之前,请检查 List#contains()元素已经存在.

Iterate your original list and add the elements to a List, but before adding them, check with List#contains() if the element is already there.

试试这个:

String[] original = input.split(" ");
List<String> finalList = new ArrayList<String>();

for (String s : original) {
    if (!finalList.contains(s)) {
        finalList.add(s);
    }
}

System.out.println("\nHere is the set list:");
displayList(finalList);
System.out.println("\n");

这篇关于删除java arraylist中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆