JAVA对两个map进行处理
高洛峰
高洛峰 2017-04-17 17:47:33
0
2
308

我有两个map的大致结构如下:

【idmap】
111 aaa
113 bbb
114 ccc
115 aaa
116 ddd

【shamap】:
1 aaa
2 bbb
3 ccc
4 ddd

需要得到的结果是:
1 aaa 111
2 bbb 113
3 ccc 114
1 aaa 115
4 ddd 116 这种的。

就是说,shamap里面存的是没有重复的,然后每个value都对应一个序列1,2,3.....
我需要做的其实就是将shamap里面的value的值的序号加到idmap里面,idmap里面相同value的序号是一样的。

我想的是在一个idmap的迭代里面再放入shamap的迭代,然后判断两个map的value是否相同再输出。但是结果总是不对

        Iterator<String> it = idmap.keySet().iterator();
            Iterator<String> it2 = shamap.keySet().iterator();
            
              while(it.hasNext()) {
                 String count = null;
                 String key = it.next();
                 String value = idmap.get(key);
          
                 while(it2.hasNext()){
                     String col = it2.next();
                     String value2 = shamap.get(col);
                     
                     if (value.equals(value2)){
                         count= col;
                     }
                    
                 }
               
                 System.out.println(count+" "+value+"  "+key);
                 
           }

结果却只显示第一个的。。不知道是哪里逻辑不对,该怎么改呢。
1 aaa 111
null bbb 112
null ccc 114
null aaa 115
null ddd 116

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
伊谢尔伦

Iterator can only iterate once, it is recommended to use entryset

巴扎黑

The iterator can only be traversed once, so the inner iterator cannot traverse the entire map every time. A simple modification is to put the line of code that obtains the shamap iterator into the first while.

PS: If you can ensure that the key and value in the shamap correspond one-to-one, you can consider using guava's BiMap, which can easily find the key from the value. This way, there is no need for two layers of nested loops, and the efficiency will be higher.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!