Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

best way to add two different object type list into one different type of list

I have one List<String> names and another list List<Amount> amountList and of two list wanted to create below list List<Example> which have both the type string and amount.

List<String> names = {"a","b","c"};



Amount.java 
{ 
 private Double amt1;
 private Double amt2;
}


Example.Java
{
private String name;
private Amount amount;
}

which is the best way to create the List<Example> example. for each name I wanted to add amount. Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A simple loop should be sufficient:

final List<String> names = List.of("a","b","c");
List<Amount> amounts = List.of(...);

final List<Example> examples = new ArrayList<>(names.size());
for (int i = 0; i < names.size(); ++i) {
  examples.add(new Example(names.get(i), amounts.get(i)));
}

But you could also use iterators:

final List<String> names = List.of("a","b","c");
final List<Amount> amounts = List.of(...);

final List<Example> examples = new ArrayList<>();

final Iterator<String> namesIterator = names.iterator();
final Iterator<Amount> amountsIterator = amounts.iterator();

while (namesIterator.hasNext() && amountsIterator.hasNext()) {
  examples.add(new Example(namesIterator.next(), amountsIterator.next()));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading