Java:有地图功能吗? [英] Java: is there a map function?

查看:127
本文介绍了Java:有地图功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要地图功能。在Java中是否有这样的东西?

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

推荐答案

从Java 6开始,JDK中没有函数的概念。

There is no notion of a function in the JDK as of java 6.

Guava 功能界面虽然和

Collections2.transform(集合< E>,函数< E,E2>)

方法提供您需要的功能。

Guava has a Function interface though and the
Collections2.transform(Collection<E>, Function<E,E2>)
method provides the functionality you require.

示例:

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

输出:

[a, 14, 1e, 28, 32]



< hr>

现在,使用Java 8,实际上有一个map函数,所以我可能会以更简洁的方式编写代码:


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

这篇关于Java:有地图功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆