【问题标题】:How to save integers from map to using the for loop如何将整数从地图保存到使用 for 循环
【发布时间】:2019-01-02 17:04:51
【问题描述】:

我有一个问题要问你,我正在尝试使用 for 循环将整数从 map 保存到数组中。下面的示例没有按我的意愿工作,因为当我显示该整数数组时,它只有 10 个元素的“2”,但我想得到 [1,2,0,0,0,0...],该代码应该更改什么?

Map<Integer, String> fooMap = new HashMap<>();
fooMap.put(1, "AB");
fooMap.put(2, "BBA");

int[] arrayOfIntegers = new int[10];

for (Map.Entry<Integer, String> values : fooMap.entrySet()) {
    int val = values.getKey();
    System.out.println(val);
    for (int index = 0; index < arrayOfIntegers.length; index++) {
        arrayOfIntegers[index] = val;
    }
}

【问题讨论】:

  • 您循环所有条目(1 -> AB 和 2 -> BBA),打印键(1 和 2),然后将该键写入数组的每个从未读取的索引。你有什么困惑?
  • 对于地图中的每个元素,您将遍历整个数组并将其中的每个索引设置为该值。

标签: java arrays dictionary


【解决方案1】:

在循环的每次迭代中,您都会覆盖整个数组。您可以改为将数组的索引保存在循环之外并使用它来更新数组:

int index = 0;
for (Integer val: fooMap.keySet()) {
    arrayOfIntegers[index] = val;
    ++index;
}

【讨论】:

  • 感谢您向我解释这一点。
【解决方案2】:

您可以使用流:

int[] arrayOfIntegers = fooMap.keySet().stream()
                              .mapToInt(k->k).toArray();

【讨论】:

    【解决方案3】:
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    
    public class stack1 {
     public static void main(String[] args) {
         Map<Integer, String> fooMap = new HashMap<>();
         fooMap.put(1, "AB");
         fooMap.put(2, "BBA");
    
         int memoryAllocated = 10;
         int[] arrayOfIntegers = new int[memoryAllocated];
         int pos =0;
    
         for (Map.Entry<Integer, String> values : fooMap.entrySet()) {
             int val = values.getKey();
             arrayOfIntegers[pos]=val;
             pos =pos+1;
         }
    
         while(pos < memoryAllocated){
             arrayOfIntegers[pos]=0;
             pos = pos+1;
         }
    
         System.out.println("Arrays : "+Arrays.toString(arrayOfIntegers));
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-09
      • 2013-03-06
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多