Given that I have the array of :
JavaScript
x
List<CustEnt> bulkList= CustRepo.fetchData();
//System.out.println(bulkList) -->
gives me :
JavaScript
CustEct(name:"kasis",age:24,surname:"kumar"),CustEct(name:"samika",age:50,surname:"sharma"),CustEct(name:"manoj",age:84surname:"kumar")
OR
bulkList.get(1) --> CustEct(name:"kasis",age:24,surname:"kumar")
I want to create a new array which is grouped by the 3rd parameter of surname object. So that my array becomes
JavaScript
ArrayFinal = [CustEct(name:"kasis",age:24,surname:"kumar"),CustEct(name:"samika",age:50,surname:"sharma")],CustEct(name:"manoj",age:84surname:"kumar")
So that when we do .get(1) we would get object of kasis and samika.
Need the help in respective to java 8. I heard that we can use the Map ,but can anyone give the small code sample or any other implementation guide.
Advertisement
Answer
A Map
tracks key-value pairs.
- Your key is the surname string.
- Your value is a list of the
CustEnt
objects carrying that surname.
JavaScript
Map<String, List<CustEnt>>
Modern syntax with streams and lambdas makes for brief code to place your objects in a map.
Something like:
JavaScript
Map<String, List<CustEnt>> map = originalList.stream.collect(Collectors.groupingBy(CustEnt::getSurename));