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!
>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()));
}