KItis
KItis

Reputation: 5646

Java Collections to filter element using regular expression

I am looking if there is a collection in java API, where I am able to retrieve the elements which are starting with some given text.

For example, If i have following elements in the collection

abc
abbb
adf
abab
dfg
cfg

if I type "a", then it should return all the elements starting with character "a".

Upvotes: 1

Views: 740

Answers (2)

M A
M A

Reputation: 72874

There is no collection that can give you this filtering out-of-the-box but you can do a simple pipeline (needs Java 8):

filteredList = collection.stream()
                         .filter(e -> e.startsWith("a"))
                         .collect(Collectors.toList());

There are third-party libraries that allow filtering collections as well:

The linked Javadoc descriptions explain exactly how each method does the filtering (i.e. whether it modifies the given collection, or it returns a new one).


Or simply using a for loop ( and before):

List<String> filteredList = new ArrayList<String>();
for(Iterator<String> iterator = collection.iterator(); iterator.hasNext();) {
    String str = iterator.next();
    if(str.startsWith("a")) {
        filteredList.add(str);
    }
 }

Upvotes: 2

Bohemian
Bohemian

Reputation: 425198

You don't need regex. In pre Java 8:

Collection<String> strings; // given this
String filter = "a";
for (Iterator<String> i = strings.iterator(); i.hasNext();)
    if (i.next().startsWith(filter))
        i.remove();

Upvotes: 3

Related Questions