プロパティ ファイル エントリで定義されているシーケンスに従って Map 内のキーを並べ替える必要があるなどの要件があります。したがって、その出力は、プロパティ エントリで定義されているユーザーのシーケンスに従って出力される必要がありTreeMap
ますComparator
。
私のプロパティファイルのエントリは
seq=People,Object,Environment,Message,Service
以下は私のコードです:
Properties prop=new Properties();
prop.load(new FileInputStream("D:\\vignesh\\sample.properties"));
final String sequence=prop.getProperty("seq");
// Display elements
final String sequence=prop.getProperty("seq");
System.out.println("sequence got here is "+sequence);
//Defined Comparator
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String key1, String key2) {
return sequence.indexOf(key1) - sequence.indexOf(key2);
}
};
SortedMap<String,String> lhm = new TreeMap<String,String>(comparator);
// Put elements to the map
lhm.put("Object", "biu");
lhm.put("Message", "nuios");
lhm.put("Service", "sdfe");
lhm.put("People", "dfdfh");
lhm.put("Environment", "qwe");
lhm.put("Other", "names");
lhm.put("Elements", "ioup"); //Not showing in output
lhm.put("Rand", "uiy"); //Not showing in output
//Iterating Map
for(Entry<String, String> entry : lhm.entrySet()) {
System.out.println(entry.getKey());
}
出力
sequence got here is People,Object,Environment,Message,Service
Other
People
Object
Environment
Message
Service
今、私はこのコードにいくつかの問題があります。
マップ内にほぼ 8 つの要素がありますが、出力には 6 つの要素しか表示されません。最後の 2 つの要素が表示されなかったのはなぜですか?
シーケンスと一致しない値が上に来る
ようになりました.下にそれらを取得したい.方法はありますか?final
ここでは、毎回プロパティを変更できないように、プロパティ ファイルから読み取る文字列を宣言しました
。最終識別子を削除すると、IDE でエラーが表示されます。どうすればそれを
回避できますか?HashMap 内のキーは、プロパティ エントリ
シーケンスと完全には一致しない可能性があります。したがって、そのシーケンスが HashMap キーに含まれているかどうかを確認する必要があります。そのために Comparator を変更する必要がありますか?