Search code examples
javamap-function

Java: is there a map function?


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...)


Solution

  • 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<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);