java - for 循环内的 while 循环不起作用

标签 java hashmap

我有一个HashMap

Map<String,String> lhm = new HashMap<String,String>();
lhm.put("Zara", "biu");
lhm.put("Mahnaz", "nuios");
lhm.put("Ayan", "sdfe");
lhm.put("Daisy", "dfdfh");
lhm.put("Qadir", "qwe");

我想根据属性文件中给出的顺序对该 HashMap 进行排序。实际上,该属性条目将按某种顺序具有键。我的属性条目将如下所示

seq=Ayan,Zara,Mahnaz,Qadir,Daisy

我为此所做的尝试是

Map<String,String> lhm = new HashMap<String,String>();
Properties prop=new Properties();
prop.load(new FileInputStream("D:\\vignesh\\sample.properties"));
// Put elements to the map
lhm.put("Zara", "biu");
lhm.put("Mahnaz", "nuios");
lhm.put("Ayan", "sdfe");
lhm.put("Daisy", "dfdfh");
lhm.put("Qadir", "qwe");

// Get a set of the entries
Set<Entry<String, String>> set = lhm.entrySet();
// Get an iterator
Iterator<Entry<String, String>> iter = set.iterator();
// Display elements
String sequence=prop.getProperty("seq");
System.out.println("sequence got here is "+sequence);
String[] resultSequence=sequence.split(",");

for(int j=0;j<resultSequence.length;j++)
{
   while(iter.hasNext()) {

     Map.Entry me = (Map.Entry)iter.next();
     String res=(String) me.getKey();

     if(res.equals(resultSequence[j]))
     {
       System.out.println("values according with the sequence is "+lhm.get(resultSequence[j]));
     }   
   }
}

我得到的输出是

sequence got here is Ayan,Zara,Mahnaz,Qadir,Daisy
values according with the sequence is sdfe

我的预期输出是

values according with the sequence is sdfe
values according with the sequence is biu
values according with the sequence is nuios
values according with the sequence is qwe
values according with the sequence is dfdfh

它正在我的 for 循环中的第一次迭代中工作。之后它也从我的 for 循环中退出。我在这里缺少什么?谢谢您的阅读。

最佳答案

它不起作用,因为您从未重置迭代器。您仅在第一次运行时匹配该字符串。尝试将迭代器放入循环中,以便为每次迭代获取一个新的迭代器,如下所示:

for(int j=0;j<resultSequence.length;j++)
{
     Iterator<Entry<String, String>> iter = set.iterator();
     while(iter.hasNext()) {
       ....
     }
}

关于java - for 循环内的 while 循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18630943/

相关文章:

android - JSON 数组到 GridView 中的 ImageView

kotlin - 更新 map 时,将 map 从 Java 传递到 Kotlin 不会编译

Java HashMap 对象,整数

java - HashMap 以非连续顺序返回值

java - 在中心找不到 Artifact gnu.trove :trove:jar:3. 0.3 (https ://repo. maven.apache.org/maven2)

java - 我正在从文本文件中读取数组,然后我应该大写字母,计算每个名称的出现次数,然后显示所有信息。

java - 尝试提取 <html>..</html> 时,substringBetween() 返回 null

node.js - 如何使用 hashmap( HSET ) 在 redis 中存储 Json

java - 关于数据建模的非常基本的问题

java - Spring java邮件: send mail impossible with yahoo