如何在Java中将一个ArrayList中的元素赋值并存储到另一个ArrayList中。

huangapple go评论57阅读模式
英文:

How to assign and store value of element from one arraylist to another in java

问题

我有来自ArrayList中的数据输出,我有以下两个ArrayList,第一个ArrayList的价格在第二个ArrayList中。
我想要使用特定物品的价格来使用一些公式计算账单。我想要存储这个值,例如:Apple=200。

> 公式:账单 = Apple + (10 * Cake)
> 
> 我已经使用了HashMap。我以前从未使用过HashMap。还有其他存储值的方式吗?

ArrayList<String> name = {Apple, Cake, ice-cream, Milk, Burger, Eggs}
ArrayList<String> values = {200, 350, 75, 80, 200, 100}
HashMap<List<String>, ArrayList<String>> nameWithvalues = new HashMap<>();
nameWithvalues.put(name, values)

Output

nameWithvalues :{[Apple, Cake, ice-cream, Milk, Burger, Eggs]=[200, 350, 75, 80, 200, 100]}
英文:

I have output from data in ArrayList, I have below two ArrayList, where the price of first ArrayList in second ArrayList.
I want to use the price for particular items to calculate the bill with some formula. I want to store the value eg. Apple=200.

> Formula: Bill = Apple + (10 * Cake)
>
> I have used HashMap.I have never used HashMap before. Or is there any
> other way to store values?

    ArrayList<String> name = {Apple, Cake, ice-cream, Milk, Burger, Eggs}
        ArrayList<String> values = {200, 350, 75, 80, 200, 100}
        HashMap<List<String>, ArrayList<String>> nameWithvalues = new HashMap<>();
                nameWithvalues.put(name, values);

Output

nameWithvalues :{[Apple, Cake, ice-cream, Milk, Burger, Eggs]=[200, 350, 75, 80, 200, 100]}

答案1

得分: 2

你可以开始一个循环,将两个 arrayList 中的值放入其中。来自第一个 arrayList 的值将作为键,另一个 arrayList 的值将作为值。

HashMap<String, Integer> nameWithValues = new HashMap<>();

for (int i = 0; i < name.length(); i++) {
    nameWithValues.put(name.get(i), values.get(i));
}
英文:

You can start a loop and put the values from both the arrayList . Value from first arrayList will be the key and other will be the value

HashMap&lt;String , Integer&gt; nameWithvalues = new HashMap&lt;&gt;();

for(int i=0 ; i &lt; name.length() ; i++ )
 {
  nameWithvalues.put(name.get(i), values.get(i));
 }

huangapple
  • 本文由 发表于 2020年9月28日 18:25:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64100380.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定