2

I have a List of Images

List<Image> images = getImages();

Image.java

public class Image {
    private String imageId;

    // getter and setter methods
    // ...
}

And I have a List<String> imageIds to replace the imageId in each Image object. What would be the best way to do it?

10
  • Can you please explain 'And I have a List<String> images to replace the imageId in each Image'? I am not sure what do you mean by replace here. Commented Jan 27, 2014 at 6:05
  • 1
    how are you identifying the relationship between each imageId and each Image object? Commented Jan 27, 2014 at 6:06
  • I need some more explanation here. Commented Jan 27, 2014 at 6:08
  • I need to replace imageId in all Image objects. For that I have List<String> with same size. Commented Jan 27, 2014 at 6:09
  • 1
    @vivek you should mention that in your question. This is an impotent part to provide an answer. Commented Jan 27, 2014 at 6:14

4 Answers 4

1

I think traversing the List<Image> and for each element call the imageID's setter will just works fine.

Even if there is a way to do it with less code, it probably uses traversing fundementally.

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

Comments

0

Iterate over the Images list and call setImageId(imageId) on it.

Iterator<String> imageIDs = imageIds.iterator();
for(Image image : images){
    image.setImageId(imageIDs.next());
}

Since both are List I am assuming order is important as it is inserted.

Comments

0

You have mention in the comment both List has same order, So you can try this.

    List<String> imageIds=new ArrayList<>();
    List<Image> images = new ArrayList<>();
    for(Image img:images){
       img.setImageId(imageIds.iterator().next());
    }

1 Comment

I don't think imageIds.iterator().next() is what you mean to do. ; )
0

You question sounds strange. It's not very clear, but if you need to add/remove/replace elements in the list, you should use ListIterator. It has a set method, which allows to replace elements.

1 Comment

If question is not clear, you can post a comment bellow the question to clarify the question. This is kind of comment than an answer.

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.