I have a List<Map <String, String>>
which contains data such as IP address, rx packets, rx bytes. eg
我有一个List
{key:address value:10.0.0.1, key:packets value:500, key:bytes value:20240}
{key:address value:10.0.0.5, key:packets value:20, key:bytes value:260}
{key:address value:10.0.0.100, key:packets value:1000, key:bytes value:503210}
How can i sort this List based on bytes? I want one output like this:
如何根据字节对此列表进行排序?我想要一个像这样的输出:
{10.0.0.100, 1000, 503210}
{10.0.0.1, 500, 20240}
{10.0.0.5, 20, 260}
edit: I get my data from API(mikrotik API) which returns List<Map <String, String>>
编辑:我从API(mikrotik API)获取数据,返回List
List<java.util.Map<String, String>> results = con.execute("mikrotik command");
2 个解决方案
#1
0
To sort based on a value of a key in a Map you can do
要根据Map中键的值进行排序,您可以执行此操作
List<Map<String, String>> listOfData =
listOfData.sort(Comparator.comparing(m -> m.get("bytes"));
In general, you should use a custom class in Java, rather than a generic collection like Map wherever you have lots of them with the same String keys
一般情况下,您应该使用Java中的自定义类,而不是像Map这样的泛型集合,只要有很多它们使用相同的String键
#2
-1
instead of using a map create a Custom class for the data with setters and getters.Implement comparator interface
而不是使用地图创建一个自定义类的数据与setter和getters.Implement比较器接口
class MyObject implements Comparator<MyObject>{
String ip;
int rxPackets;
int rxbytes;
//getters and setters for each element
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getrxbytes.compareTo(o2.getrxbytes());
}
Then use Collections.sort(pass List<MyObject> here);
然后使用Collections.sort(在这里传递List
#1
0
To sort based on a value of a key in a Map you can do
要根据Map中键的值进行排序,您可以执行此操作
List<Map<String, String>> listOfData =
listOfData.sort(Comparator.comparing(m -> m.get("bytes"));
In general, you should use a custom class in Java, rather than a generic collection like Map wherever you have lots of them with the same String keys
一般情况下,您应该使用Java中的自定义类,而不是像Map这样的泛型集合,只要有很多它们使用相同的String键
#2
-1
instead of using a map create a Custom class for the data with setters and getters.Implement comparator interface
而不是使用地图创建一个自定义类的数据与setter和getters.Implement比较器接口
class MyObject implements Comparator<MyObject>{
String ip;
int rxPackets;
int rxbytes;
//getters and setters for each element
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getrxbytes.compareTo(o2.getrxbytes());
}
Then use Collections.sort(pass List<MyObject> here);
然后使用Collections.sort(在这里传递List