Java中类似Python的列表理解 [英] Python-like list comprehension in Java
问题描述
由于Java不允许将方法作为参数传递,你使用什么技巧来实现Python中的列表推理这样的Python?
Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?
我有一个列表(ArrayList)字符串。我需要使用一个函数转换每个元素,以便我得到另一个列表。我有几个函数,它们将String作为输入,并返回另一个String作为输出。如何创建一个通用方法,可以将列表和函数作为参数给出,这样我就可以获得一个列表,并处理每个元素。从字面意义上讲是不可能的,但是我应该使用什么技巧?
I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as output. How do I make a generic method which can be given the list and the function as parameters so that I can get a list back with each element processed. It is not possible in the literal sense, but what trick should I use ?
另一种选择是为每个较小的字符串处理函数编写一个新函数,它只是循环在整个列表中,这有点不太酷。
The other option is to write a new function for each smaller String-processing function which simply loops over the entire list, which is kinda not so cool.
推荐答案
基本上,您创建了一个Function接口:
Basically, you create a Function interface:
public interface Func<In, Out> {
public Out apply(In in);
}
然后将匿名子类传递给您的方法。
and then pass in an anonymous subclass to your method.
您的方法可以将函数应用于原位的每个元素:
Your method could either apply the function to each element in-place:
public static <T> void applyToListInPlace(List<T> list, Func<T, T> f) {
ListIterator<T> itr = list.listIterator();
while (itr.hasNext()) {
T output = f.apply(itr.next());
itr.set(output);
}
}
// ...
List<String> myList = ...;
applyToListInPlace(myList, new Func<String, String>() {
public String apply(String in) {
return in.toLowerCase();
}
});
或创建一个新的列表
(基本上创建从输入列表到输出列表的映射):
or create a new List
(basically creating a mapping from the input list to the output list):
public static <In, Out> List<Out> map(List<In> in, Func<In, Out> f) {
List<Out> out = new ArrayList<Out>(in.size());
for (In inObj : in) {
out.add(f.apply(inObj));
}
return out;
}
// ...
List<String> myList = ...;
List<String> lowerCased = map(myList, new Func<String, String>() {
public String apply(String in) {
return in.toLowerCase();
}
});
哪一个更可取决于您的使用案例。如果您的清单非常大,那么就地解决方案可能是唯一可行的解决方案;如果您希望将许多不同的函数应用于同一原始列表以生成许多衍生列表,您将需要 map
版本。
Which one is preferable depends on your use case. If your list is extremely large, the in-place solution may be the only viable one; if you wish to apply many different functions to the same original list to make many derivative lists, you will want the map
version.
这篇关于Java中类似Python的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!