关于Map集合

鱼尾陈雨meimei 2011-11-17 04:02:51
我在遍历一个Map集合的时候
例如说一个Map里面有1,2,3,4,5五个元素
在遍历的时候,便利到1的时候我需要取1和2两个元素,在遍历2的时候要取2和3两个元素,以此类推
该怎么实现?
...全文
148 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
leilei0932_java 2011-11-17
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 cym9055 的回复:]

key 的类型是字符串

引用 2 楼 leilei0932_java 的回复:
Java code

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
map.put(5, 5);
……
[/Quote]

由于map是以键值形式存储的,所以如果键是字符串的话要满足你的要求也必须是字符形式的数字
稍加修改就行了:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("1", 1);
map.put("2", 2);
map.put("3", 3);
map.put("4", 4);
map.put("5", 5);
for (String i : map.keySet()) {

System.out.print(map.get(i));
if(Integer.parseInt(i)+1<=map.size()){
System.out.print(",");
System.out.println(map.get(Integer.parseInt(i)+1+""));
}else{
System.out.print(",");
System.out.println(map.get("1"));
}
}

鱼尾陈雨meimei 2011-11-17
  • 打赏
  • 举报
回复
key 的类型是字符串

[Quote=引用 2 楼 leilei0932_java 的回复:]
Java code

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
map.put(5, 5);
……
[/Quote]
jc8futao 2011-11-17
  • 打赏
  • 举报
回复
要用LinkHashMap,HashMap是不保证迭代顺序的~!~!
绝世酱油瓶 2011-11-17
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 qybao 的回复:]

Java code
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
map.put(5, 5);
for (Integer i : map.keySet()) {
System.out.prin……
[/Quote]
+1
funfenffun 2011-11-17
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 qybao 的回复:]

Java code
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
map.put(5, 5);
for (Integer i : map.keySet()) {
System.out.prin……
[/Quote]
+1,取2个的话就不适合用iterator了
qybao 2011-11-17
  • 打赏
  • 举报
回复
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
map.put(5, 5);
for (Integer i : map.keySet()) {
System.out.printf("%d, %d\n", map.get(i), map.get(i==5 ? 1 : i+1));
}
leilei0932_java 2011-11-17
  • 打赏
  • 举报
回复

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
map.put(5, 5);
for (Integer i : map.keySet()) {
System.out.print(map.get(i));
if(i+1<=map.size()){
System.out.print(",");
System.out.println(map.get(i+1));
}
}
aYuan1129 2011-11-17
  • 打赏
  • 举报
回复
Map m = new TreeMap();
m.put("o1", 1);
m.put("o2", 2);
m.put("o3", 3);
m.put("o4", 4);
m.put("o5", 5);
Set keySet = m.keySet();
for (Iterator it = keySet.iterator(); it.hasNext();) {
Object one = m.get(it.next());
Object two;
if (it.hasNext()) {
two = m.get(it.next());
}
}

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧