delete duplicates in java arraylist

前端 未结 4 1630
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 14:16

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

4条回答
  •  旧时难觅i
    2021-01-23 15:03

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

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

    -or-

    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.

    EDIT: Try this:

    String[] original = input.split(" ");
    List finalList = new ArrayList();
    
    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");
    

提交回复
热议问题