gpt4 book ai didi

java - 如何按键对Java中的 map 进行排序,但如果键是(字符串+数字)的组合

转载 作者:行者123 更新时间:2023-11-29 10:10:23 26 4
gpt4 key购买 nike

我创建了一个名为 result 的 map 。

在 sortByKeys 方法中,由于我的键是带有数字值的字符串,我已将它们转换为整数键类型 Map,然后对它们进行排序。

Map<String, String> unsortMap = new TreeMap<String, String>();
unsortMap.put("room~1", "e");
unsortMap.put("room~2", "y");
unsortMap.put("room~10", "n");
unsortMap.put("room~4", "j");
unsortMap.put("room~5", "m");
unsortMap.put("room~3", "f");

Set set2 = unsortMap.entrySet();
Iterator iterator2 = set2.iterator();

while (iterator2.hasNext()) {
/* Iterate */
Map.Entry me2 = (Map.Entry) iterator2.next();
String key = (String) me2.getKey();
Object value = (Object) me2.getValue();
System.out.println("Key ==>" + key + " Value ==>" + value);
}

# Current Output:#
/* current result */
Key ==>room~1 Value ==>e
Key ==>room~10 Value ==>n
Key ==>room~2 Value ==>y
Key ==>room~3 Value ==>f
Key ==>room~4 Value ==>j
Key ==>room~5 Value ==>m

#Expected O/p:#
/* required result */
Key ==>room~1 Value ==>e
Key ==>room~2 Value ==>y
Key ==>room~3 Value ==>f
Key ==>room~4 Value ==>j
Key ==>room~5 Value ==>m
Key ==>room~10 Value ==>n

最佳答案

创建自定义键对象

public class Key implements Comparable<Key>{
String name;
int id;

public Key(String name, int id) {
this.name = name;
this.id = id;
}

@Override
public int compareTo(Key o) {
if(Objects.equals(name, o.name)){
return Integer.compare(id, o.id);
}else{
return name.compareTo(o.name);
}
}

@Override
public String toString() {
return name +"~"+ id;
}

@Override
public boolean equals(Object o){
...
@Override
public int hashCode(){
...
}

并像这样使用它:

    Map<Key, String> unsortMap = new TreeMap<>();
unsortMap.put(new Key("room", 5), "e");

但是如果字符串总是有空间,你应该在键中使用它

关于java - 如何按键对Java中的 map 进行排序,但如果键是(字符串+数字)的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39270787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com