I want to remove duplicate values from array list i.e String which has been updated from MySQL
Asked
Active
Viewed 917 times
0

Aldeguer
- 821
- 9
- 32

viral vathas
- 1
- 1
- 1
- 5
-
you can check this link: https://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist – Laxman Sep 28 '17 at 07:40
4 Answers
1
First check the query if you can eliminate duplicate values from the query itself. Even if you can't , then use LinkedHashMap.

RKT
- 174
- 1
- 4
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);

Amit
- 30,756
- 6
- 57
- 88
-
-
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 – viral vathas Sep 28 '17 at 07:38
-
@viralvathas , please read https://stackoverflow.com/help/how-to-ask , you will be able to paste your code after your read this. – Amit Sep 28 '17 at 07:41
-
@viralvathas , I also added the code in my Edit, where you can create set using existing array-list. – Amit Sep 28 '17 at 08:53
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);

Mostch Romi
- 531
- 1
- 6
- 19
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.

Shirkam
- 744
- 6
- 20