Skip to content

Instantly share code, notes, and snippets.

@dgouyette
Created May 10, 2011 09:46
Show Gist options
  • Save dgouyette/964192 to your computer and use it in GitHub Desktop.
Save dgouyette/964192 to your computer and use it in GitHub Desktop.
Filter class and turns it into collection
import static com.google.common.collect.Maps.filterEntries;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.base.Predicate;
public class FilterMapTest {
public static Collection<String> filtreMapByKeyToCollection(Map<String, String> map) {
Predicate<Entry<String, String>> keyStartWithOption = new Predicate<Entry<String, String>>() {
@Override
public boolean apply(Entry<String, String> o) {
if (o != null && o.getKey().startsWith("option_"))
return true;
return false;
}
};
return filterEntries(map, keyStartWithOption).values();
}
@Test
public void filtreMapTest() {
Map<String, String> options = new HashMap<String, String>();
options.put("option_1", "valeur 1");
options.put("option_2", "valeur 2");
options.put("anotherKey", "whatever");
options.put("anotherKey", null);
long start = System.currentTimeMillis();
Collection<String> filtredOption = filtreMapByKeyToCollection(options);
System.out.println(System.currentTimeMillis() - start + " ms");
Assert.assertFalse(filtredOption.contains("whatever"));
Assert.assertTrue(filtredOption.contains("valeur 1"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment