Java Get multiple items from a collection

Do Java collections have a built-in method for returning multiple items from this collection? For example, the list below contains n items, some of which are duplicated in the list. How can I get all the elements where value = "one"? I understand that it would be very easy to write my own method to achieve this functionality, I just wanted to make sure that I lacked the built-in method for 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

+4
source share
4 answers

Google Collections are predicates for this purpose.

+2
source

There is no built-in method, but Apache Commons has a select method in CollectionUtils that will get all elements matching a specific criteria. Usage example:

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

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

You could also use Multiset from google collections and called m.count("one") , which would be much more efficient.

+2
source

I think you could do the trick to save the elements of this list that are in another list with the keepall method of the Collection class link text . In another list, you can add only "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); 
0
source

Source: https://habr.com/ru/post/1301956/


All Articles