I need a map function. Is there something like this in Java already?
(For those who wonder: I of course know how to implement this trivial function myself...)
There is no notion of a function in the JDK as of java 6.
Guava has a Function interface though and the
Collections2.transform(Collection
method provides the functionality you require.
Example:
// example, converts a collection of integers to their
// hexadecimal string representations
final Collection input = Arrays.asList(10, 20, 30, 40, 50);
final Collection output =
Collections2.transform(input, new Function(){
@Override
public String apply(final Integer input){
return Integer.toHexString(input.intValue());
}
});
System.out.println(output);
Output:
[a, 14, 1e, 28, 32]
These days, with Java 8, there is actually a map function, so I'd probably write the code in a more concise way:
Collection hex = input.stream()
.map(Integer::toHexString)
.collect(Collectors::toList);