Java 中是否有与 Python 的 map 函数等效的函数?

发布于 2024-10-08 18:50:31 字数 122 浏览 3 评论 0原文

我想轻松地将 A 类对象的集合(列表)转换为 B 类对象的集合,就像 Python 的 map 函数所做的那样。是否有任何“众所周知的”实现(某种库)?我已经在 Apache 的 commons-lang 中搜索过它,但没有成功。

I would like to easily transform a collection (list) of objects of class A to a collection of objects of class B, just as Python's map function does it. Is there any "well-known" implementation of this (some kind of library)? I've already searched for it in Apache's commons-lang but with no luck.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

指尖凝香 2024-10-15 18:50:31

Java 8开始,这可以通过Stream API 使用适当的映射器 Function 我们将使用它来转换类 A< 的实例/code> 到类 B 的实例。

伪代码如下:

List<A> input = // a given list of instances of class A
Function<A, B> function = // a given function that converts an instance 
                          // of A to an instance of B
// Call the mapper function for each element of the list input
// and collect the final result as a list
List<B> output = input.stream().map(function).collect(Collectors.toList());

这是一个具体示例,它将 StringList 转换为 List Integer 使用 Integer.valueOf(String) 作为映射器函数:

List<String> input = Arrays.asList("1", "2", "3");
List<Integer> output = input.stream().map(Integer::valueOf).collect(Collectors.toList());
System.out.println(output);

输出:

[1, 2, 3]

对于 Java 的早期版本,您仍然可以使用 来自 Google GuavaFluentIterable 来替换 Stream 并使用 com.google.common.base.Function而不是 java.util.function.Function 作为映射器函数

前面的示例将被重写为下一个:

List<Integer> output = FluentIterable.from(input)
    .transform(
        new Function<String, Integer>() {
            public Integer apply(final String value) {
                return Integer.valueOf(value);
            }
        }
    ).toList();

输出:

[1, 2, 3]

Starting from Java 8, it can be done thanks to the Stream API using an appopriate mapper Function that we will use to convert our instances of class A to instances of class B.

The pseudo code would be:

List<A> input = // a given list of instances of class A
Function<A, B> function = // a given function that converts an instance 
                          // of A to an instance of B
// Call the mapper function for each element of the list input
// and collect the final result as a list
List<B> output = input.stream().map(function).collect(Collectors.toList());

Here is a concrete example that will convert a List of String to a List of Integer using Integer.valueOf(String) as mapper function:

List<String> input = Arrays.asList("1", "2", "3");
List<Integer> output = input.stream().map(Integer::valueOf).collect(Collectors.toList());
System.out.println(output);

Output:

[1, 2, 3]

For previous versions of Java, you can still use FluentIterable from Google Guava to replace the Stream and use com.google.common.base.Function instead of java.util.function.Function as mapper function.

The previous example would then be rewritten as next:

List<Integer> output = FluentIterable.from(input)
    .transform(
        new Function<String, Integer>() {
            public Integer apply(final String value) {
                return Integer.valueOf(value);
            }
        }
    ).toList();

Output:

[1, 2, 3]
人事已非 2024-10-15 18:50:31

仍然不存在的

函数式编程功能将添加到Java 8 - Project Lambda

我认为 Google Guava 最适合您目前的需求

still not exist

functional programming features will be added in Java 8 - Project Lambda

I think Google Guava is best for your needs now

小糖芽 2024-10-15 18:50:31

There are several functional libraries mentioned here, most of which probably cover map:

http://www.cs.chalmers.se/~bringert/hoj/
programmer (includes Java 5.0 generics
support). Little documentation.

http://jakarta.apache.org/commons/sandbox/functor/
doesn't look like it is maintained,
doesn't support generics. Little
documentation.

http://devnet.developerpipeline.com/documents/s=9851/q=1/ddj0511i/0511i.html
library.

http://functionalj.sourceforge.net

http://www.functologic.com/orbital/

http://jga.sourceforge.net/
programming in java (includes
generics). Looking forward to more
documentation, perhaps better
organization of the API.

浊酒尽余欢 2024-10-15 18:50:31

您可以尝试使用 guava,但您可能会发现,如果您使用匿名类,它会比仅使用循环更复杂且更长。

List<OldType> list1 =
List<NewType> list2 = new ArrayList<NewType>(list1.size());
for(OldType element: list1);
   list2.add(transform(element));

值得记住的是,Java 不是一种函数式语言,通常最好只使用循环。也许当Java有闭包时......叹息。

You can try guava, but you are likely to find that if you use an anonymous class its will be more complicated and longer than just using a loop.

List<OldType> list1 =
List<NewType> list2 = new ArrayList<NewType>(list1.size());
for(OldType element: list1);
   list2.add(transform(element));

Its worth remembering that Java is not a functional language and its often better to just use a loop. Perhaps when Java has closures .... sigh.

烈酒灼喉 2024-10-15 18:50:31

查看 lambdaj 及其 转换方法

Take a look at lambdaj and its convert method

舞袖。长 2024-10-15 18:50:31

从 Java 8 开始,Python 地图的 Java 等效项称为...地图!

package stackOverflow;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


public class ListMapExample
{

    public static void main(String[] args) {
        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
        List<int[]> arrays = integers.stream().map(size -> new int[size])
                .collect(Collectors.toList());
        arrays.forEach(ary -> System.out.println(Arrays.toString(ary)));
    }

}

此示例将整数列表转换为具有相应大小的数组列表:

[0]
[0, 0]
[0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0, 0]

您还可以在 map 内编写多个语句:

List<String> strings = Arrays.asList("1", "2", "3", "4", "5");
Stream<int[]> arraysStream = strings.stream().map(string -> {
    int size = Integer.valueOf(string);
    int size2 = size * 2;
    return new int[size2];
});
arraysStream.map(Arrays::toString).forEach(System.out::println);

Since Java 8, the Java equivalent for Python's map is called ... map !

package stackOverflow;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


public class ListMapExample
{

    public static void main(String[] args) {
        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
        List<int[]> arrays = integers.stream().map(size -> new int[size])
                .collect(Collectors.toList());
        arrays.forEach(ary -> System.out.println(Arrays.toString(ary)));
    }

}

This examples converts a list of integers to a list of arrays with the corresponding size :

[0]
[0, 0]
[0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0, 0]

You can also write more than one statement inside map :

List<String> strings = Arrays.asList("1", "2", "3", "4", "5");
Stream<int[]> arraysStream = strings.stream().map(string -> {
    int size = Integer.valueOf(string);
    int size2 = size * 2;
    return new int[size2];
});
arraysStream.map(Arrays::toString).forEach(System.out::println);
琉璃梦幻 2024-10-15 18:50:31

这是我的解决方案:

public abstract class MapF<T,S>
    {
        public abstract T f(S s) throws Exception;

        public List<T> map(List<S> input) throws Exception
        {
            LinkedList<T> output = new LinkedList<T>();
            for (S s: input)
                output.add(f(s));
            return output;
        }
    }

简单地,扩展此类定义函数 f 并调用列表上的方法映射。

This is my solution:

public abstract class MapF<T,S>
    {
        public abstract T f(S s) throws Exception;

        public List<T> map(List<S> input) throws Exception
        {
            LinkedList<T> output = new LinkedList<T>();
            for (S s: input)
                output.add(f(s));
            return output;
        }
    }

Simply, extends this class defining your function f and call the method map on the list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文