Java: is there a map function?
There is no notion of a function in the JDK as of java 6.
Guava has a Function interface though and theCollections2.transform(Collection<E>, Function<E,E2>)
method provides the functionality you require.
Example:
// example, converts a collection of integers to their
// hexadecimal string representations
final Collection<Integer> input = Arrays.asList(10, 20, 30, 40, 50);
final Collection<String> output =
Collections2.transform(input, new Function<Integer, String>(){
@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<String> hex = input.stream()
.map(Integer::toHexString)
.collect(Collectors::toList);
Since Java 8, there are some standard options to do this in JDK:
Collection<E> in = ...
Object[] mapped = in.stream().map(e -> doMap(e)).toArray();
// or
List<E> mapped = in.stream().map(e -> doMap(e)).collect(Collectors.toList());
See java.util.Collection.stream()
and java.util.stream.Collectors.toList()
.