0

I want to remove duplicate values from array list i.e String which has been updated from MySQL

enter image description here

1

4 Answers 4

1

First check the query if you can eliminate duplicate values from the query itself. Even if you can't , then use LinkedHashMap.

Sign up to request clarification or add additional context in comments.

Comments

0

you have to use LinkedHashSet, which store only unique data i.e no duplicate data allow in LinkedHashSet. also,it store data in same sequence as ArrayList.

or use this code-

List<String> list = new ArrayList<>();

// add elements to list, including duplicates

Set<String> hs = new LinkedHashSet<>();

hs.addAll(list);

list.clear();

list.addAll(hs);

Comments

0

As its a String, you can use Set data structure to hold these values, which doesn't contain the duplicate values.

Read more about set here.

Sample code of HashSet :-

public class SetEx {

public static void main(String args[])
{
    Set<String> set = new HashSet<String>();
    set.add("abc");
    set.add("aaa");
    set.add("fgh");
    set.add("hdsjkadhka");
    set.add("abc");
    set.add("aaa");

    System.out.println("set of Strings " + set);
}

}

Edit :- if you want to create a HashSet from existing ArrayList then use below code :-

 ArrayList<String> list = new ArrayList<>();
        list.add("amit");
        list.add("amit");

        Set<String> copySet = new HashSet<>(list);

        System.out.println("set of string "+ copySet);

4 Comments

can you give a sample code bro please am new to java
yes I cannot paste my code , it shows please add some context to explain, am doing but still not allowed to submit question can you contact me on whatsapp
@viralvathas , please read stackoverflow.com/help/how-to-ask , you will be able to paste your code after your read this.
@viralvathas , I also added the code in my Edit, where you can create set using existing array-list.
0

Using Java 8 Streams:

List<String> listWithDups = getListWithDupes();
//do something else before remove dupes
List<String> result = listWithDups.stream()
    .distinct()
    .collect(Collector.toList());
//Use your new list

Also, if you obtain duplicated values from your SQL query, you should consider using DISTINCT keyword in your query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.