Get Unique Values from Arraylist in Java

Creating an ArrayList of unique items in an ArrayList in Java

If you don't want duplicates but want to use an ArrayList a quick fix would be to move all the items into a HashSet (which does not allow duplicates), clear the ArrayList and then add the items from the HashSet back into the ArrayList.

Getting unique values from two arraylists with Collections

Make a duplicate of the first list and use it to removeAll from second list. Because if you remove duplicates from first list and then compare it with second list all the values will be unique as the duplicates were already removed from first list.

Collection<String> listDir = new ArrayList(Arrays.asList("1","2", "3", "4", "5", "6", "7"));
Collection<String> listDirCopy = new ArrayList<>();
listDirCopy.addAll(listDir);
Collection<String> listDB = new ArrayList(Arrays.asList("1","3", "5", "7", "9"));
List<String> destinationList = new ArrayList<String>();

listDir.removeAll(listDB);
listDB.removeAll(listDirCopy);

destinationList.addAll(listDir);
destinationList.addAll(listDB);
System.out.println(destinationList);

Create an ArrayList of unique values

Create an Arraylist of unique values

You could use Set.toArray() method.

A collection that contains no duplicate elements. More formally, sets
contain no pair of elements e1 and e2 such that e1.equals(e2), and at
most one null element. As implied by its name, this interface models
the mathematical set abstraction.

http://docs.oracle.com/javase/6/docs/api/java/util/Set.html

Select distinct fields of an ArrayList of Class X

 items.stream()
.collect(Collectors.groupingBy(X::getBrand)) // group your items by brand
.values().stream() // stream map values
.map(e->e.get(0)) // for each brand get first element in brand list
.collect(Collectors.toList());

If you cann't use java8 / streams

    Map<String,List<X>> map = new HashMap<>();
for(X item : items){
if(!map.containsKey(item.getBrand())){
map.put(item.getBrand(), new ArrayList<>());
}else{
map.get(item.getBrand()).add(item);
}
}
List<X> result = new ArrayList<>();
for(Map.Entry<String,List<X>> e : map.entrySet()){
result.add(e.getValue().get(0));
}

How can I get distinct values of a specific column in arrayList

The method get(String) is undefined for the type Personne

you should use getIDT_GCT() instead

How to get distinct values from array list in Android

Welcome to the stackoverflow.

Instead to save it in an ArrayList<> use a HashSet<> that will only save unique values,

If the list contains objects of classes defined in your code you will have to overwrite the equals() method in that class in order to distinguish which objects are different from each other and also the hashcode() method



Related Topics



Leave a reply



Submit