1

I have a list of instances where I need to create another list of instances using the instances in the first list. As the example shown below, I can use a foreach or a for loop. Is there a better way to do this more efficiently?

List<Mesage> messages; 
List<ArchMessage> archMessages = new ArrayList<>();
for(Message message : messages) {
       archMessages.add(new ArchMessage(message));
}
5
  • What is the relationship between Message and ArcMessage classes? Commented Dec 26, 2017 at 18:36
  • You haven't defined your problem/solution space clearly enough. What do you mean by efficiently? More readable? More maintainable? Best performance? Most scalable? Commented Dec 26, 2017 at 18:37
  • Are there other ways to do this? Yes. More efficiently? No. Commented Dec 26, 2017 at 22:11
  • @PM77-1 ArchMessage means the archived Message. Commented Jan 9, 2018 at 8:53
  • @scottb what I meant by efficiently is the best performance and scalable. Commented Jan 9, 2018 at 8:54

4 Answers 4

2

You can use Java 8 Streams:

List<ArchMessage> archMessages =
    messages.stream()
            .map(message -> new ArchMessage(message))
            .collect(Collectors.toList());

or

List<ArchMessage> archMessages =
    messages.stream()
            .map(ArchMessage::new)
            .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

0

If you're unable to use streams from Java 8, Apache Commons Collections library provides the following:

http://commons.apache.org/proper/commons-collections/

Collection<ArchMessage> archMessages = CollectionUtils.collect(messages, new Transformer() {
    public Object transform(Object o) {
        return new ArchMessage((Mesage) o);
    }
});

Comments

0

That's as efficient as it gets but let's say your code could benefit from parallelism then using the streams API would be ideal as we can get parallelism for free by using parallelStream e.g.

 List<ArchMessage> resultSet = messages.parallelStream()
                                       .map(ArchMessage::new)
                                       .collect(Collectors.toList());

Other than that your current approach seems good and readable.

Comments

0

Feedback to your recherche: I would recommend to don't use a foreach. It will throw your efficient down cause of an inner request at each. I would recommend to use a for each time..

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.