Java: is there a map function?

前端 未结 6 1780
天命终不由人
天命终不由人 2020-12-04 13:52

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

6条回答
  •  无人及你
    2020-12-04 14:33

    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, Function)
    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);
    

提交回复
热议问题