I was writing some code that I sometimes need, not often, and was wondering why it required so many lines of code. I needed to create a new collection with the strings returned from a method in the objects of another collection. I might do this three times on three different methods of that class. I thought there might be something in guava to help me. Something like:
collection = Iterators.collectNotNull( myCollection, new Function...{
public String apply( MyObject input ) {
String value = input.getStringValue();
if ( StringUtils.isEmpty( value )
return null;
return value; } );
I mean that is even too many lines of code for me. But either way I basically wrote the above for times when I need it.
So the question is, can anyone do this more simply with less code? You can use existing mainstream libraries like Apache commons or Guava. Reflection is okay if you want to remove the need to create the anonymous inner to get the method that will return the value. The above is my best attempt but I had to write the reusable "collectNotNull" method. I'd prefer not to have to.