I have a List<Map <String, String>>
which contains data such as IP address, rx packets, rx bytes. eg
{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>>
List<java.util.Map<String, String>> results = con.execute("mikrotik command");
To sort based on a value of a key in a Map you can do
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
instead of using a map create a Custom class for the data with setters and getters.Implement comparator interface
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.