循环添加地图值

时间:2018-11-27 08:50:22

标签: java android dictionary for-loop

我正在尝试在Java中将一些值放入循环中,但完成循环后我只能得到一个值。我试图找到一些东西,但找不到任何东西...

 List<Double> prices = new ArrayList<>();
 Map<Boolean, Double> map = new HashMap<Boolean, Double>();

 for (Rewards rewardsPrice : Preferences.getRewards()) {
     map.put(rewardsPrice.isPreference(), rewardsPrice.getCredit()); // when finish the loop I only have 1 value, when prices have a lot of more
 }

 Set<Boolean> keys = map.keySet(); // The set of keys in the map.
 Iterator<Boolean> keyIter = keys.iterator();

 while (keyIter.hasNext()) {
      Boolean key = keyIter.next();
      Double value = map.get(key);
      map.put(key, value);
 }

2 个答案:

答案 0 :(得分:1)

这里的键的类型为布尔值,因为布尔值在任何给定时间只能有2个值,TRUE,FALSE和NULL(作为对象)映射最多可以有3个条目。将所有6个值都放在一个键值(TRUE / FALSE / NULL)上的可能性很高。 Map始终针对键维护单个值。

Map<Boolean, Double> map = new HashMap<Boolean, Double>(); 

答案 1 :(得分:0)

List<Double> prices = new ArrayList<>();
Map<String, Rewards> map = new HashMap<String, Rewards>();

for (Rewards rewardsPrice : Preferences.getRewards()) {
    if (rewardsPrice.isPreference()) {
        prices.add(rewardsPrice.getCredit());
    }
}