I have List<Custom>
where Custom is
class Custom {
public int id;
public String name;
}
How to get number how many items have different names ? Is there any easier way than put all in set and get set size ?
I have List<Custom>
where Custom is
class Custom {
public int id;
public String name;
}
How to get number how many items have different names ? Is there any easier way than put all in set and get set size ?
The set solution you describe sounds nice and simple; however, you'll have to override the equals
and hashCode
methods on the Custom
class to make use of Java's hashing functionality.
A faster solution might be to put just the names in a set (since the String class already has the necessary hashing functionality). Although, if you plan to store instances of the Custom class in hashing data structures (such as HashSet or HashMap, etc.) then you'll need to override those methods anyway.
Put names to set:
Set<String> set = new HashSet<String>();
for (Custom c : list) {
set.add(c.name);
}
System.out.println(set.size());
You can also fill set with your Custom
objects if you use appropriate Comparator that compares names only:
int nDifferentNames = new HashSet<Custom>(list, new Comparator<Custom>() {
public int compare(Custom one, Custom two) {
return one.name.compareTo(two.name);
}
}).size();