Remove duplicates from an ArrayList in Java

0 votes

I was taking a test and was stuck with this program can someone help me find a solution?

I want to remove all the duplicate elements in an arraylist.

eg:

1 2 3 1 2 3 4 5 4 5 6  7 8 7 6 7 8
Output:
1 2 3 4 5 6 7 8
Mar 5 in Java by Naman
275 views

1 answer to this question.

0 votes

Here is the function for doing this.

// Function to remove duplicates from an ArrayList
public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list)
{
    // Create a new ArrayList
    ArrayList<T> newList = new ArrayList<T>();
    // Traverse through the first list
    for (T element : list) {
        // If this element is not present in newList then add it
        if (!newList.contains(element)) {
            newList.add(element);
        }
    }
    // return the new list
    return newList;
}
answered Mar 5 by Heena

Related Questions In Java

0 votes
2 answers

Remove duplicate elements from an ArrayList in Java

List<String> al = new ArrayList<>(); // add elements ...READ MORE

answered Jul 26, 2018 in Java by Sushmita
• 6,880 points
76 views
0 votes
2 answers

How can we remove an element from an array in Java?

You can use ArrayUtils class remove method which ...READ MORE

answered May 24, 2018 in Java by UshaK
101 views
0 votes
2 answers

One line initialization of an ArrayList object in Java

In Java 8 or earlier: List<String> string = ...READ MORE

answered Jul 26, 2018 in Java by samarth295
• 2,190 points
145 views
0 votes
4 answers

Remove extra spaces from string in java

import java.util.regex.Matcher; import java.util.regex.Pattern; String pattern="[\\s]"; String replace=""; part="name=john age=13 year=2001"; Pattern ...READ MORE

answered Sep 10, 2018 in Java by parth295
• 4,620 points
86 views
0 votes
1 answer

Are arrays equivalent to objects in Java ?

Yes; the Java Language Specification writes: In the Java ...READ MORE

answered May 10, 2018 in Java by Rishabh
• 3,540 points
58 views
0 votes
1 answer

Remove objects from an array in Java?

We can use external libraries: org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int ...READ MORE

answered Jun 26, 2018 in Java by scarlett
• 1,280 points
48 views
0 votes
1 answer

Performance difference of if/else vs switch statement in Java

The thing you are worried about is ...READ MORE

answered Jul 26, 2018 in Java by geek.erkami
• 2,320 points
413 views
+1 vote
3 answers

What is the syntax to declare and initialize an array in java?

You can use this method: String[] strs = ...READ MORE

answered Jul 25, 2018 in Java by samarth295
• 2,190 points
325 views
0 votes
1 answer

How to get rid of TLE in Java?

The TLE (Time limit exceed) problem occurs ...READ MORE

answered Mar 5 in Java by Disha
136 views
0 votes
1 answer

What are the different ways of comparing Strings in Java?

The different ways of comparing string in ...READ MORE

answered Mar 5 in Java by Wasim
44 views