2

It's been a while since I last used Java, so forgive me if the question is stupid. In Ruby, I use .map quite a lot. Is there something similar in Java or do I have to iterate over the Array?

In Ruby, instead of

output = []
input.each do |elem|
  output << SomeClass.new(elem)
end

I can write

output = input.map { |elem| SomeClass.new(elem) }

2 Answers 2

2

Yes, with Java 8 you can use streams to iterate over collections implicitly. For example:

final List<String> strings = Arrays.asList("Me", "You");
final List<String> reducedStrings = strings.stream().map(s -> s.substring(1)).collect(Collectors.toList()); // [ "e", "ou" ]

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toList--

Sign up to request clarification or add additional context in comments.

Comments

0

Since Java 8 and its support for lambda expressions and its stream API:

List<SomeClass> result = someCollection.stream()
                                       .map(SomeClass::new)
                                       .collect(Collectors.toList());

If you're really using an array and not a collection (you should prefer collections almost always), then you can create a strem over the array using

Arrays.stream(array)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.