Map List have ID, Device Name, New PIN and Created Date.
Now using below method, I am getting all record present against Moto device
mpinRecordList.removeIf(map -> !map.containsValue("Moto"));
but how to get the record by recent date.
CodePudding user response:
Using Java 8
You can use the below approach to get the sorted data as required.
Approach Here:
- I have filter the list based on
"Moto"
device name as required and then usesorted()
usingCompartor.comparing()
in which you can pass the attribute by which you want to sort the list, here i have passed the date and after that i have used.reversed()
in order to get the latest data first.
Code:
Device.java
public class Device {
private int id;
private String name;
private long pin;
private Date date;
public Device(int id, String name, long pin, Date date) {
this.id = id;
this.name = name;
this.pin = pin;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getPin() {
return pin;
}
public void setPin(long pin) {
this.pin = pin;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Device{"
"id=" id
", name='" name '\''
", pin=" pin
", date=" date
'}';
}
}
Test.java
public class Test {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss.SSS");
Device d1 = new Device(1,"Samsung",934195,format.parse("15-10-2022 02:18:53.909"));
Device d2 = new Device(4,"Moto",129876,format.parse("15-10-2022 02:40:11.149"));
Device d3 = new Device(5,"Moto",671598,format.parse("15-10-2022 02:55:01.879"));
Device d4 = new Device(6,"Moto",305483,format.parse("15-10-2022 03:15:01.879"));
Device d5 = new Device(7,"Moto",190352,format.parse("15-10-2022 03:16:11.109"));
Device d6 = new Device(8,"Sony",278160,format.parse("15-10-2022 03:30:12.809"));
List<Device> sortedListOfMotoDevice = Arrays.asList(d1,d2,d3,d4,d5,d6).stream().filter(x -> x.getName().equals("Moto"))
.sorted(Comparator.comparing(Device::getDate).reversed()).collect(Collectors.toList());
System.out.println(sortedListOfMotoDevice);
}
}
Output:
[Device{id=7, name='Moto', pin=190352, date=Sat Oct 15 03:16:11 IST 2022}, Device{id=6, name='Moto', pin=305483, date=Sat Oct 15 03:15:01 IST 2022}, Device{id=5, name='Moto', pin=671598, date=Sat Oct 15 02:55:01 IST 2022}, Device{id=4, name='Moto', pin=129876, date=Sat Oct 15 02:40:11 IST 2022}]