我試圖SortedMap在我的一個春季項目中使用定制比較器。這是一個 SortedMap,我試圖按字符串的后半部分(這是關鍵)進行排序。密鑰“A:123”的示例。我添加了一個自定義比較器以確保 SortedMap 是按整數順序而不是字符串順序進行的。這是一個簡化的示例代碼,我在里面有一個帶有 SortedMap 的類:class TestObject{ private SortedMap<String, String> myMap = new TreeMap<String, String>({ new Comparator<String>() { @Override public int compare(String s1, String s2) { int m1 = Integer.parseInt(O1.split(":")[1]); int m2 = Integer.parseInt(O2.split(":")[1]); return m1- m2; } }); void setMap(SortedMap<String, String> maps){ myMap = maps; } void getMap(){ return myMaps; }}在我的主要功能中,我做了:class UpperClass{ @Autowired TestObject object1; public setNewMap(){ SortedMap<String, String> myInput = new TreeMap<String, String>({ //my comparator }); myInput.put("A:10000", "XXX"); myInput.put("A:500","XXX"); myInput.put("A:200","XXX"); object1.setMap(myInput); } pubic getResult(){ SortedMap<String, String> result = object1.getMap(); } }所以我遠程調試我的應用程序。類定義中的比較器似乎從未被調用過。我逐行打印,而 myInput 通過輸出維護字符串的順序:A:200A:500A:10000但是,當我的應用程序調用 get Result 時,它會打印出:A:10000A:200A:500這是字符順序。所以我想知道我是否通過在類定義中放置比較器做錯了什么。
1 回答

千巷貓影
TA貢獻1829條經驗 獲得超7個贊
您的語法不正確。使用 lambda 的方法:
new TreeMap<String, String>((a, b) -> a.length() - b.length());
使用 Comparator 的實用方法:
new TreeMap<String, String>(Comparator::comparingInt(String::length));
老式:
new TreeMap<String, String>(new Comparator<String>() {
public int compare(String a, String b) {
return a.length - b.length;
});
第二個(使用 Comparator 的實用程序)絕對是三個中最好的。請注意,您可以鏈接(表示:首先對這個事物進行排序,如果它們相同,然后對這個事物進行排序,但反過來:您可以這樣做)。
添加回答
舉報
0/150
提交
取消