Java:有地图功能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3907394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:40:15  来源:igfitidea点击:

Java: is there a map function?

javamap-function

提问by Albert

I need a mapfunction. Is there something like this in Java already?

我需要一个地图功能。Java中已经有这样的东西了吗?

(For those who wonder: I of course know how to implement this trivial function myself...)

(对于那些想知道的人:我当然知道如何自己实现这个微不足道的功能......)

采纳答案by Sean Patrick Floyd

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

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

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

Guava有一个Function接口,该 方法提供了你需要的功能。
Collections2.transform(Collection<E>, Function<E,E2>)

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:

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

Collection<String> hex = input.stream()
                              .map(Integer::toHexString)
                              .collect(Collectors::toList);

回答by wheaties

There is a wonderful library called Functional Javawhich handles many of the things you'd want Java to have but it doesn't. Then again, there's also this wonderful language Scala which does everything Java should have done but doesn't while still being compatible with anything written for the JVM.

有一个很棒的库,称为Functional Java,它可以处理您希望 Java 拥有但它没有的许多东西。再说一次,还有这种美妙的语言 Scala,它可以完成 Java 应该做的所有事情,但仍然与为 JVM 编写的任何内容兼容。

回答by Pedro Rolo

This is another functional lib with which you may use map: http://code.google.com/p/totallylazy/

这是您可以使用地图的另一个功能库:http: //code.google.com/p/totallylazy/

sequence(1, 2).map(toString); // lazily returns "1", "2"

回答by Emmanuel Touzery

Be very careful with Collections2.transform()from guava. That method's greatest advantage is also its greatest danger: its laziness.

Collections2.transform()从番石榴中要非常小心。这种方法的最大优点也是最大的危险:它的懒惰。

Look at the documentation of Lists.transform(), which I believe applies also to Collections2.transform():

查看 的文档Lists.transform(),我相信它也适用于Collections2.transform()

The function is applied lazily, invoked when needed. This is necessary for the returned list to be a view, but it means that the function will be applied many times for bulk operations like List.contains(java.lang.Object) and List.hashCode(). For this to perform well, function should be fast. To avoid lazy evaluation when the returned list doesn't need to be a view, copy the returned list into a new list of your choosing.

该函数被延迟应用,在需要时调用。这对于返回的列表是一个视图是必要的,但这意味着该函数将被多次应用于批量操作,如 List.contains(java.lang.Object) 和 List.hashCode()。为了让这个表现良好,函数应该很快。当返回的列表不需要是视图时,为了避免延迟评估,请将返回的列表复制到您选择的新列表中。

Also in the documentation of Collections2.transform()they mention you get a live view, that change in the source list affect the transformed list. This sort of behaviour can lead to difficult-to-track problems if the developer doesn't realize the way it works.

同样在Collections2.transform()他们提到的文档中,您可以获得实时视图,源列表中的更改会影响转换后的列表。如果开发人员没有意识到它的工作方式,这种行为可能会导致难以跟踪的问题。

If you want a more classical "map", that will run once and once only, then you're better off with FluentIterable, also from Guava, which has an operation which is much more simple. Here is the google example for it:

如果你想要一个更经典的“地图”,它只会运行一次,那么你最好使用FluentIterable,同样来自 Guava,它的操作要简单得多。这是它的谷歌示例:

FluentIterable
       .from(database.getClientList())
       .filter(activeInLastMonth())
       .transform(Functions.toStringFunction())
       .limit(10)
       .toList();

transform()here is the map method. It uses the same Function<> "callbacks" as Collections.transform(). The list you get back is read-only though, use copyInto()to get a read-write list.

transform()这是地图方法。它使用与Collections.transform(). 您返回的列表是只读的,用于copyInto()获取读写列表。

Otherwise of course when java8 comes out with lambdas, this will be obsolete.

否则当然当 java8 与 lambdas 一起出现时,这将过时。

回答by leventov

Since Java 8, there are some standard options to do this in JDK:

从 Java 8 开始,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().

java.util.Collection.stream()java.util.stream.Collectors.toList()

回答by IPP Nerd

Even though it's an old question I'd like to show another solution:

即使这是一个老问题,我也想展示另一个解决方案:

Just define your own operation using java generics and java 8 streams:

只需使用 java 泛型和 java 8 流定义您自己的操作:

public static <S, T> List<T> map(Collection<S> collection, Function<S, T> mapFunction) {
   return collection.stream().map(mapFunction).collect(Collectors.toList());
}

Than you can write code like this:

比你可以写这样的代码:

List<String> hex = map(Arrays.asList(10, 20, 30, 40, 50), Integer::toHexString);