Hi all,
can any one tell me how to find unique values in array list?
Thanks in advance..

What kind of values or object are you talking about? Do you have a compare method to work with? There are various ways to deal with it, but it depends on what object you are storing in your array list and how they can be compared.

> can any one tell me how to find unique values in array list?

Assuming your items of the `List' implement an appropriate equals/hashCode() method or the Comparable interface, converting it to a `Set' would be the simplest way to get the unique elements.

thanks Taywin and ~s.o.s~

@Taywin all the values from the database tables then i stored it in array list now i need to find unique values in it .

@~s.o.s~ could you explain me with some code
thanks

You need to tell us the type of values you have in the `List'. Assuming you have simple strings in the list, you can do:

// untested
final List<String> lst = Arrays.asList("a", "b", "c", "a", "c", "b");
final Set<String> set = new HashSet<String>(lst);
System.out.printf("Original list: %s%n", lst);
System.out.printf("Unique values: %s%n", set);

@~s.o.s~ (-: why you have to sent here your post twice :-)

@~s.o.s~ (-: why you have to sent here your post twice :-)

Sometimes happens when there is lag on your internet connection or on server side.
~s.o.s~ Set is obvious solution :P

thanks for all of your replies

dear ~s.o.s~,
Its working but the order is changed. List shows only unique values but some strange order..

Right, because Set guarantees unique elements, not necessarily in sorted order. If you need to maintain the order of elements, use `TreeSet<String>`. Just make sure the objects you insert in the TreeSet implement natural ordering (by implementing Comparable) or be ready to provide your own custom ordering (implement Comparator). Anyways, here is the extension snippet:

public static void main(String[] args) throws Exception {
	final List<String> lst = Arrays.asList("a", "b", "c", "a", "c", "b");
	final Set<String> set1 = new HashSet<String>(lst);
	final Set<String> set2 = new TreeSet<String>(lst);
	System.out.printf("Original list: %s%n", lst);
	System.out.printf("Unique values: %s%n", set1);
	System.out.printf("Unique values sorted: %s%n", set2);
}

thanks a lot ~s.o.s~,
Its working perfectly..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.