views:

214

answers:

4

Hello,

Do Java collections have a built-in method to return multiple items from that collection? For example, the list below has n elements, some of which are duplicated in the list. How could I get all elements where the value = "one"? I realize it would be very easy to write my own method to achieve such functionality, I just wanted to make sure I am not missing a built in method to do this.

List<String> ls=new ArrayList<String>();
ls.add("one");
ls.add("two");
ls.add("three");
ls.add("one");
ls.add("one");

//some type of built in function????
//ls.getItems("one");
//should return elements 0,3,4

Thanks

+2  A: 

Google Collections have Predicates for this purpose.

Roman
+2  A: 

There isn't a built-in method, but Apache Commons has a select method in CollectionUtils that will get all the elements that match some criterion. Example usage:

List<String> l = new ArrayList<String>();

// add some elements...

// Get all the strings that start with the letter "e".
Collection beginsWithE = CollectionUtils.select(l, new Predicate() {
  public boolean evaluate(Object o) {
    return ((String) o).toLowerCase().startsWith("e");
  }
);
John Feminella
At the moment I don't see any advantage of Apache Collections over Google Collections. They stopped developing this library and it's the main problem.
Roman
A: 

I think you could do the trick of retaining the elements of this list which are in another list with the retainall method of Collection class link text. In the other list you can add only the "one" object.

List<String> ls=new ArrayList<String>();
ls.add("one");
ls.add("two");
ls.add("three");
ls.add("one");
ls.add("one");

List<String> listToCompare = new ArrayList<String>();
listToCompare.add("one");
ls.retainAll(listToCompare);
Javi
+2  A: 

In this example, it's enough to know the number of times "one" appears in the list, which you can get with java.util.Collections.frequency(ls, "one").

You could also have been using a Multiset from google-collections, and called m.count("one"), which would be much more efficient.

Kevin Bourrillion