利用java 怎么将Map转化为二维数组?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
实例代码:
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Test { public static void main(String[] args) { int a = 0, b = 0, c = 0; // 第一种:通过Map.keySet()遍历Map及将Map转化为二维数组 Map<String, String> map1 = new HashMap<String, String>(); map1.put("012013012013", "张三"); map1.put("012013012014", "张四"); String[][] group1 = new String[map1.size()][2]; System.out.println("第一种:通过Map.keySet()遍历map1的key和value"); for (String key : map1.keySet()) { System.out.println("key = " + key + " and value = " + map1.get(key)); group1[a][0] = key; group1[a][1] = map1.get(key); a++; } System.out.println("map1.size()为:" + map1.size() + ",a为:" + a + ",group1数组的长度为:" + group1.length); System.out.println("----------------------------------------------------"); for(int n = 0; n < group1.length; n++) { System.out.println("key = " + group1[n][0] + " and value = " + group1[n][1]); } // 第二种:通过Map.entrySet()使用iterator()遍历Map及将Map转化为二维数组 Map<String, String> map2 = new HashMap<String, String>(); map2.put("112013012013", "李三"); map2.put("112013012014", "李四"); System.out.println("\n" + "第二种:通过Map.entrySet()使用iterator()遍历map2的key和value"); Iterator<Map.Entry<String, String>> iterator = map2.entrySet().iterator(); String[][] group2 = new String[map2.size()][2]; while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); System.out.println("key = " + entry.getKey() + " and value = " + entry.getValue()); group2[b][0] = entry.getKey(); group2[b][1] = entry.getValue(); b++; } System.out.println("map2.size()为:" + map2.size() + ",b为:" + b + ",group2数组的长度为:" + group2.length); System.out.println("----------------------------------------------------"); for(int n = 0; n < group2.length; n++) { System.out.println("key = " + group2[n][0] + " and value = " + group2[n][1]); } // 第三种:通过Map.entrySet()遍历遍历Map及将Map转化为二维数组 Map<String, String> map = new HashMap<String, String>(); map.putAll(map1); map.putAll(map2); String[][] group3 = new String[map.size()][2]; System.out.println("\n" + "第三种:通过Map.entrySet()遍历map的key和value "); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key = " + entry.getKey() + " and value = " + entry.getValue()); group3[c][0] = entry.getKey(); group3[c][1] = entry.getValue(); c++; } System.out.println("map.size()为:" + map.size() + ",c为:" + c + ",group3数组的长度为:" + group3.length); System.out.println("----------------------------------------------------"); for(int n = 0; n < group3.length; n++) { System.out.println("key = " + group3[n][0] + " and value = " + group3[n][1]); } } }
当前名称:利用java怎么将Map转化为二维数组-创新互联
文章位置:https://www.cdcxhl.com/article46/epoeg.html
成都网站建设公司_创新互联,为您提供网站内链、网站导航、App开发、App设计、品牌网站建设、电子商务
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联