3

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 ?

maerics
  • 151,642
  • 46
  • 269
  • 291
Damir
  • 54,277
  • 94
  • 246
  • 365
  • 1
    I would put in into set as you said... But maybe some pros know better way. – noisy cat Feb 06 '12 at 18:38
  • See my answer for your same question: http://stackoverflow.com/questions/9165222/count-number-of-items-with-property/9166314#9166314 – kornero Feb 06 '12 at 20:08

2 Answers2

5

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.

maerics
  • 151,642
  • 46
  • 269
  • 291
2

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();
AlexR
  • 114,158
  • 16
  • 130
  • 208