我有这张地图,其中包含姓名,姓氏和其他个人信息,例如:
jhon:[doe];
ann:[devil]
我想要的是按字母顺序对它们进行排序,但是这种结构对我来说是新的。 如何按字母顺序排序?这是我的代码
private String uid;
private String username;
private String fullName;
private String name;
private String lastname;
private String email;
private String phone;
private Map<String, List<PorticoProfile>> profiles;
public Map<String, List<PorticoProfile>> getProfiles() {
if (profiles == null) {
profiles = new LinkedHashMap<>();
}
return profiles;
}
public void setProfiles(Map<String, List<PorticoProfile>> profiles) {
this.profiles = profiles;
}
public void setFullName(String fullName) {
this.fullName = fullName;
if (fullName.contains(" ")){
String[] nameParts = fullName.split(" ");
this.name = nameParts[0];
this.lastname = nameParts[1];
}
}
@Override
public String toString(){
final String BREAK = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
sb.append("uid: ").append(this.uid).append(BREAK);
sb.append("username: ").append(this.username).append(BREAK);
sb.append("fullname: ").append(this.fullName).append(BREAK);
sb.append("email: ").append(this.email).append(BREAK);
sb.append("phone: ").append(this.phone).append(BREAK);
if (this.getProfiles().size() > 0){
sb.append("profiles: ").append(this.profiles.keySet().stream().collect(Collectors.joining(", "))).append(BREAK);
}
return sb.toString();
}
答案 0 :(得分:2)
我认为您应该签出另一个接口:SortedMap(https://docs.oracle.com/javase/8/docs/api/java/util/SortedMap.html)
Map<String, Object> m = new HashMap<>();
m.put("john", "doe");
m.put("ann", "devil");
SortedMap<String, Object> s = new TreeMap<>(m);
s.entrySet().forEach(System.out::println);
答案 1 :(得分:1)
使用group1.objects.get(pk=self.kwargs['pk'])
-https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html
TreeMap
会保留将数据添加到Map的顺序,LinkedHashMap
会根据密钥(在您的情况下为TreeMap
即名称
String
答案 2 :(得分:1)
尝试:
Map<String, List<MyClass>> sorted = map.entrySet()
.stream()
.sorted(Comparator.comparing(Map.Entry::getKey)) // sort by key
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));