viral vathas
viral vathas

Reputation: 1

removing duplicate values from sql table added in arraylist

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

enter image description here

Upvotes: 0

Views: 981

Answers (4)

Shirkam
Shirkam

Reputation: 754

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.

Upvotes: 0

Amit
Amit

Reputation: 32386

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);

Upvotes: 0

Mostch Romi
Mostch Romi

Reputation: 541

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);

Upvotes: 0

RKT
RKT

Reputation: 314

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

Upvotes: 1

Related Questions