2010-02-21 43 views
4

Java集合是否具有内置方法以从集合中返回多个项目?例如,下面的列表中有n元素,其中一些元素在列表中重复。我怎么能得到值=“一”的所有元素?我意识到编写我自己的方法来实现这样的功能会非常容易,我只是想确保我不会错过内置方法来执行此操作。Java从集合中获取多个项目

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 

感谢

+0

编辑误读问题 – dangerstat 2010-02-21 15:58:46

+0

http://stackoverflow.com/questions/122105/java-what-is-the-best-way-to-filter-a-collection – Roman 2010-02-21 16:05:40

回答

2

有没有内置的方法,但Apache Commons has a select methodCollectionUtils这将获得所有符合某些标准的元素。用法示例:

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"); 
    } 
); 
+0

目前我没有看到任何Apache Collections比Google Collections更有优势。他们停止开发这个库,这是主要问题。 – Roman 2010-02-21 16:18:03

0

我想你可以保留该名单是与集合类link text的方法的retainAll另一个列表中的元素的把戏。在另一个列表中,您只能添加“一个”对象。

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); 
2

在这个例子中,它足以知道的次数“一”出现在列表中,您可以用java.util.Collections.frequency(ls, "one")得到。

您也可以使用谷歌收藏中的Multiset,并将其称为m.count("one"),效率会更高。