while循环里面for循环不起作用

Vig*_*ino 0 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");
Run Code Online (Sandbox Code Playgroud)

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

seq=Ayan,Zara,Mahnaz,Qadir,Daisy
Run Code Online (Sandbox Code Playgroud)

我对此尝试的是

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]));
     }   
   }
}
Run Code Online (Sandbox Code Playgroud)

我之后得到的输出是

sequence got here is Ayan,Zara,Mahnaz,Qadir,Daisy
values according with the sequence is sdfe
Run Code Online (Sandbox Code Playgroud)

我的预期产量是

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
Run Code Online (Sandbox Code Playgroud)

它正在我的for循环中进行第一次迭代.之后它也从我的for循环退出.我在这里缺少什么?感谢阅读.

blg*_*lgt 5

它不起作用,因为你永远不会重置你的迭代器.您只匹配第一次运行时的字符串.尝试将迭代器放在循环中,为每次迭代获取一个新的迭代器,如下所示:

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

  • 我根本不会建议这个解决方案(*即使在我的梦中*).以这种方式对地图或任何集合进行排序实际上是滥用可用的整个排序算法. (2认同)