A process that extracts only those that meet the conditions from an array or list. With Perl, you can easily write as follows (remember)
sample.pl
my @array = ('001', '901', '201', '010', '999', '311');
my @result = grep { /1$/ } @array;
After investigating whether Java can do the same, it seems that ListUtils # select () can do something similar.
Sample.java
List<String> list = Arrays.asList("001", "901", "201", "010", "999", "311");
List<String> result = ListUtils.select(list, new Predicate<String>() {
@Override
public boolean evaluate(String arg0) {
//At the end'1'When is attached
return StringUtils.endsWith(arg0, "1");
}
});
System.out.println(result.toString()); //=> [001, 901, 201, 311]
I tried to make Predicate an anonymous inner type, but which is better to implement Predicate in my class? The latter feels more like "old writing". This time I wrote a sample source with a list of strings, but I think it will be more effective if you want to extract from a list of beans.
Is it like this when writing without using ListUtils # select ()? It made me feel familiar. The usual pattern that the nesting of if statements gets deeper and deeper as the conditions become more complicated.
Sample2.java
List<String> list = Arrays.asList("001", "901", "201", "010", "999", "311");
List<String> result = new ArrayList<String>();
for (String s : list) {
if (s.endsWith("1")) {
result.add(s);
}
}
System.out.println(result.toString()); //=> [001, 901, 201, 311]
Recommended Posts