Valores únicos en un List

Para obtener valores únicos en un List<String> collection, pueden ocupar esto:


package Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

public class UniqueValues {
public static void main(String[] args) {
      String[] words = 
{"juan", "pedro", "luis","juan", "pedro", "luis","juan", "pedro", "luis"};
           
List<String> oldList = Arrays.asList(words); 
List<String> uniqueList = new ArrayList<String>(
new HashSet<String>(oldList));
System.out.println("Resultado:");
for (String string : uniqueList) {
System.out.println("\t - " + string);
}
}
}


_____________________________________________________________

Si lo quieren hacer en un objeto, se requiere implementar: hashCode() y equals() de la clase a usar:


package Test;

public class Element {
int id;
String name;
int age;

public Element(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}

/**
* @return the id
*/
public int getId() {
return id;
}

/**
* @param id
*            the id to set
*/
public void setId(int id) {
this.id = id;
}

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name
*            the name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* @return the age
*/
public int getAge() {
return age;
}

/**
* @param age
*            the age to set
*/
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
    if (o instanceof Element) {
        Element other = (Element) o;
        return this.id == other.getId();
    }
    return false;
}
@Override
public int hashCode() {
return this.id;
}
}

Y ocupan el mismo código para filtrar valores únicos:

package Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

public class UniqueValues {
public static void main(String[] args) {
Element[] entities = new Element[9];
entities[0] = new Element (1, "A" ,5);
entities[1] = new Element (2, "B" ,5);
entities[2] = new Element (3, "C" ,5);
entities[3] = new Element (1, "A" ,5);
entities[4] = new Element (2, "B" ,5);
entities[5] = new Element (3, "C" ,5);
entities[6] = new Element (1, "A" ,5);
entities[7] = new Element (2, "B" ,5);
entities[8] = new Element (3, "C" ,5);
            
List<Element> uniqueList = 
new ArrayList<Element>(
new HashSet<Element>(
Arrays.asList(entities)));
System.out.println("Resultado:");
for (Element element : uniqueList) {
System.out.println("\t - " + element.getId());
}
}
}





Comentarios