Write a filter loop in 20 seconds using Eclipse templates

We’re still waiting for closures to come to  Java – the saga continues. Until then we’ll need to write the filter boilerplate code  manually. Filter loops often take an input array/collection, match each element with a condition and, if the condition matches, adds the element to another, filtered list. Here’s an example:

List filteredNames = new ArrayList();

for (String name : names) { //names is the original String Collection/array
    if (name.contains("Sam")) {
        filteredNames.add(name);
    }
}

This code is tedious, error-prone and a time-waster. It takes a minute or two or even longer to write without any errors.

You can use Eclipse templates to generate a filter loop in about 20 seconds. If you haven’t worked with templates before, see this post for an overview.

I’ve created a template that produces a List declaration, enhanced for loop, if statement and an add to the filtered list. The list’s type is taken from the nearest array/collection in scope so should be a fairly good match. It even generates import statements for the List and ArrayList.

You can either import the template (recommended; much faster) or create the template manually.

Import the template (recommended)

Download the template below, then import it into Eclipse.

Create the template manually

Alternatively, create the template with the following settings. The template code’s a bit tricky because it does a lot.

Name filter
Context Java statements
Pattern

List<${type:elemType(list)}> ${filteredList} = new ArrayList<${type}>();

for (${type} ${element:newName(type)} : ${list:var(java.util.Collection)}) {
    if (${cursor}) {
        ${filteredList}.add(${element});
    }
}${:import(java.util.List, java.util.ArrayList)}

Check out the overview of variables if you’re unsure of what the code means.

Related Tips

Support Eclipse On E

Comments are closed.