I want to create a condition such that if the products have the same model, i want to set newID
's (A, B, C). Below table is the sample data which i'm returning as a List<MyDTO>
when getAllListValue()
method is called.
sample data:
pID prodName Model Year
10 PN1 ABX 1999
11 PN2 ABX 1999
12 PN3 ABX 2000
13 PN4 XP 2002
14 PN5 xP 2003
15 PN6 HP 2006
16 PN7 LX 2008
17 PN8 LX 2009
PN1
and model ABX
i want to set newID
as A.PN2
and model ABX
i want to set newID
as B.PN3
and model ABX
i want to set newID
as CPN4
and XP
- set newID
as APN5
and XP
- set newID
as BPN6
and HP
- set newID
as Asample code:
public class MyDTO {
private String pID;
private String productName;
private String model;
private String year;
private String newID;
// getter & setter
}
public class UseLoop {
//logic
List<MyDTO> dtoList = getAllListValue();
//here i want to iterate the list and set the newID (A,B,c) for the products with same model
for(MyDTO dto : dtoList) {
//here how can i compare with previous object and assign the newID if the product has the same model.
}
}
You could have a Map<String, Character>
wich keys are model names and values are incremented characters for new ids.
Map<String, Character> map = new HashMap<>();
List<MyDTO> dtoList = getAllListValue();
for (MyDTO dto : dtoList) {
// put 'A' in the map if the model name is not present yet,
// increment character otherwise
Character c = map.merge(dto.getModel(), 'A', (k, v) -> (char) (v + 1));
dto.setNewID(c.toString());
}
This will produce something like:
MyDTO{pID='10', productName='PN1', model='ABX', year='1999', newID='A'}
MyDTO{pID='11', productName='PN2', model='ABX', year='1999', newID='B'}
MyDTO{pID='12', productName='PN3', model='ABX', year='2000', newID='C'}
MyDTO{pID='13', productName='PN4', model='XP', year='2000', newID='A'}
MyDTO{pID='14', productName='PN5', model='XP', year='2003', newID='B'}
MyDTO{pID='15', productName='PN6', model='HP', year='2006', newID='A'}
MyDTO{pID='16', productName='PN7', model='LX', year='2008', newID='A'}
MyDTO{pID='17', productName='PN8', model='LX', year='2009', newID='B'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With