自从我上次使用 Java 以来已经有一段时间了,所以如果这个问题很愚蠢,请原谅我。在 Ruby 中,我经常使用 .map
。 Java 中有类似的东西吗?还是我必须迭代数组?
在 Ruby 中,而不是
output = []
input.each do |elem|
output << SomeClass.new(elem)
end
我会写
output = input.map { |elem| SomeClass.new(elem) }
最佳答案
是的,在 Java 8 中,您可以使用流来隐式迭代集合。例如:
final List<String> strings = Arrays.asList("Me", "You");
final List<String> reducedStrings = strings.stream().map(s -> s.substring(1)).collect(Collectors.toList()); // [ "e", "ou" ]
引用: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toList--
关于java - 将每个值映射到 Java 数组(或类似数组)中,就像在 Ruby 中一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25273221/