Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate the loop and set a new value based on the conditional check - java

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
  • For PN1 and model ABX i want to set newID as A.
  • For PN2 and model ABX i want to set newID as B.
  • For PN3 and model ABX i want to set newID as C
  • For PN4 and XP - set newID as A
  • For PN5 and XP - set newID as B
  • For PN6 and HP - set newID as A
  • ..

sample 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.
    }
}
like image 501
user222 Avatar asked Feb 06 '18 20:02

user222


1 Answers

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'}
like image 191
Kirill Simonov Avatar answered Oct 21 '22 17:10

Kirill Simonov