如何按关键字对地图进行排序?
我的地图结构是这样的
Map<String, List<Mobile>> mobiles = new HashMap<String, List<Mobile>>();
mobiles.put("Samsung", ListOfMobileModels);
mobiles.put("Nokia", ListOfMobileModels);
mobiles.put("Apple", ListOfMobileModels);
mobiles.put("Blackberrey", ListOfMobileModels);
/** Sort Like below**/
mobiles.put("Apple", ListOfMobileModels);
mobiles.put("Blackberrey", ListOfMobileModels);
mobiles.put("Samsung", ListOfMobileModels);
mobiles.put("Nokia", ListOfMobileModels);
我在另一个地图(例如Apple-1,Blackberry-2,Samsung-3,Nokia-4)中有移动排名列表
如何使用流或任何比较器对地图进行排序?
答案 0 :(得分:0)
看看这个例子:
SortedMap<String, String> fileExtensions = new TreeMap<>();
// Adding new key-value pairs to a TreeMap
fileExtensions.put("python", ".py");
fileExtensions.put("c++", ".cpp");
fileExtensions.put("kotlin", ".kt");
fileExtensions.put("golang", ".go");
fileExtensions.put("java", ".java");
// Printing the TreeMap (Output will be sorted based on keys)
System.out.println(fileExtensions);
}
似乎是您要寻找的。 Source
基于此,您可以创建一个Enum和一个类Comparator:
import java.util.*;
public class Main2 {
public static void main(String[] args) {
SortedMap<RankComparator,List<Mobile>> mobiles = new TreeMap<>();
List<Mobile> mobiles1 = new ArrayList<>();
mobiles.put(new RankComparator(Rank.Samsung), mobiles1);
mobiles.put(new RankComparator(Rank.Nokia), mobiles1);
mobiles.put(new RankComparator(Rank.Apple), mobiles1);
mobiles.put(new RankComparator(Rank.Blackberry), mobiles1);
((TreeMap<RankComparator, List<Mobile>>) mobiles).entrySet().forEach(e -> System.out.println(e.getKey().rank));
}
}
class Mobile{
Rank rank;
public Mobile(Rank rank) {
this.rank = rank;
}
}
enum Rank{
Apple(1),
Blackberry(2),
Samsung(3),
Nokia(4);
int rank;
Rank(int i) {
this.rank = i;
}
}
class RankComparator implements Comparable<RankComparator>{
Rank rank;
public RankComparator(Rank rank) {
this.rank = rank;
}
@Override
public int compareTo(RankComparator otherRank) {
return this.rank.rank - otherRank.rank.rank;
}
}
输出->
Apple
Blackberry
Samsung
Nokia