0

プロパティ ファイル エントリで定義されているシーケンスに従って 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 を変更する必要がありますか?

4

2 に答える 2

0

まず第一に、 で見つけることができない部分文字列をindexOf返します。-1String

を挿入しているときは"Other"、 returnとreturnがマップの最初の位置に追加されindexOf("Other")ます。-1indexOf("People")0"Other"

ただし、他の文字列を追加すると、 に対してテストされ"Other"、 が返されます-1。残念ながら、他のすべての要素もプロパティ値の文字列に含まれていないため、 が返され-1ます。つまりsequence.indexOf(key1) - sequence.indexOf(key2)は で0あり、それらはすべて に等しいと見なされ"Other"ます。

于 2013-09-06T08:52:53.477 に答える