I have a Catalog
bean with the following properties:
catalog_id catalog_name catalog_price catalog_title
catalog_id
is not unique, there can be multiple Catalog
object with the same id
.
Having a list of Catalog
objects, I want to collect all with the same id
and in a second for loop I want to loop with through the number of occurance of that id
.
Let say :
catalogList2.stream() .collect(Collectors.groupingBy(Catalog::getId, Collectors.counting())) .entrySet() .stream() .map(p->"catalog id--->"+p.getKey()+" -"+p.getValue()).forEach(System.out::println);
From the above code I am able to get the below output:
catalog id--->17553 -- 8 catalog id--->545 -- 8 catalog id--->546 -- 6 catalog id--->40962 -- 16 catalog id--->901 -- 12
But, after that I want to do like below : ( its just a structure I want to implement)
for(Catalog cat1:p.getKey()){ for(int i=0;i<p.getValue();i++){ System.out.println("Name -->"+cat1.get(i))); //Something i will do here. } }
I am not sure how to implement this structure.
Update
Am getting the message in my eclipse Lambda expression's parameter catalog cannot redeclare another local variable defined in an enclosing scope.
when am trying to add 2nd sysout :
catalogList2.stream() .collect(Collectors.groupingBy(Catalog::getId)) .forEach((id, catalogs) -> { System.out.println("Catalog id : " + id + " : " + catalogs.size()); catalogs.forEach(catalog -> { System.out.println("Name -->"+catalog.getCatalog_attr_name()); System.out.println("Value --->"+catalog.getCatalog_attr_value()); }); });
Update 2
Am getting this message in eclipse Local variable catalog defined in an enclosing scope must be final or effectively final
at the line String catalogName=catalog.getCatalog_name(); // getting error on this line
Please find my code here ;
JSONObject jsonObj=null; JSONArray respArray=new JSONArray(); catalogList2.stream() .collect(Collectors.groupingBy(Catalog::getId)) .forEach((id, catalogs) -> { System.out.println("Catalog id : " + id + " : " + catalogs.size()); String catalogName=catalog.getCatalog_name(); // getting error on this line String longDescriptionStr = catalogName.concat("_long_description"); String descriptionStr = catalogName.concat("_description"); jsonObj.put("catalog_id", id); catalogs.forEach(c -> { String longDescription=null; String description=null; String catalogAttrName = c.getCatalog_attr_name(); if(StringUtils.equalsIgnoreCase(catalogAttrName, longDescriptionStr)) { longDescription = c.getCatalog_attr_value(); } if(StringUtils.equalsAnyIgnoreCase(catalogAttrName, descriptionStr)) { description = c.getCatalog_attr_value(); } jsonObj.put("description", description); jsonObj.put("longDescription", longDescription); }); respArray.put(jsonObj); }); System.out.println("Printing JSON Array --->"+respArray.toString());