One Cup Black Coffee

Search Tutorial

Result Tutorial

Tampilkan postingan dengan label Type Collection Of Java. Tampilkan semua postingan
Tampilkan postingan dengan label Type Collection Of Java. Tampilkan semua postingan

Jumat, 13 Juni 2008

Sample Of Hash ( One of Type Collection In Java )

A Set is a Collection that contains unique elements (i.e., no duplicate elements). 
The collections framework contains several Set implementations,
including HashSet and TreeSet. HashSet stores its elements in a hash table, and TReeSet stores its elements in a tree.
U can uses a HashSet to remove duplicate strings from a List. Recall that both List and Collection are generic types,
so creates a List that contains String objects, and passes a Collection of Strings to method printNonDuplicates.

import
java.util.List;
import
java.util.Arrays;
import
java.util.HashSet;
import
java.util.Set;
import
java.util.Collection;
public class SetTest   {
private static final String colors[] = { "red", "white", "blue",
"green", "gray", "orange", "tan", "white", "cyan",
"peach"
, "gray", "orange" };
// create and output ArrayList
public SetTest() {
List list = Arrays.asList( colors );
System.out.printf( "ArrayList: %s\n", list );
printNonDuplicates( list );
}
    private void printNonDuplicates( Collection collection ){
// create a HashSet
Set set = new HashSet( collection );
System.out.println( "\nNonduplicates are: " );
        // Model Out Print From Java 6               
for
( String s : set )
System.out.printf( "%s ", s );
System.out.println();
}
    public static void main( String args[] )     {
new SetTest();
}
}

Result Is :

ArrayList: [red, white, blue, green, gray, orange, tan, white, cyan, peach, gray, orange]
Nonduplicates are:
red cyan white tan gray green orange blue peach