I have one bean class Hotel in which data members are HotelName
, HotelCity
, HotelContact
.
Now I want to save that data in Hashmap in a way where map Key should be City and all the hotel names should be which belongs to city should be in map values. I am able to do that using Collectors.groupby()
. However I am not able to get the HotelName, instead I am getting Hotel
object address. Please help where I am mistaking. Here is code which I attempted:
class Hotel {
private String hotelName;
private String hotelCity;
private String hotelPhNo;
/*their getter setter methods*/
}
public static void main(String[] args) {
List<Hotel> ol = new ArrayList<Hotel>();
Hotel h1 = new Hotel("H1","Pune","123");
Hotel h2 = new Hotel("H2","Mumbai","109");
Hotel h3 = new Hotel("H3","Pune","1123");
Hotel h4 = new Hotel("H4","Mumbai","123");
Hotel h5 = new Hotel("H5","Ujjain","123");
Hotel h6 = new Hotel("H6","Indore","123");
Hotel h7 = new Hotel("H7","Sehore","123");
Hotel h8 = new Hotel("H8","Pune","123");
ol.add(h1);
ol.add(h2);
ol.add(h3);
ol.add(h4);
ol.add(h5);
ol.add(h6);
ol.add(h7);
ol.add(h8);
Map<String, List<Hotel>> res = ol.stream().collect(Collectors.groupingBy(Hotel:: getHotelCity));
res.forEach((a,b)->System.out.println("City:"+a+" with Hotels: "+b));
}
With this I am getting output like:
City:Ujjain with Hotels: [Hotel@7ba4f24f]
City:Pune with Hotels: [Hotel@3b9a45b3, Hotel@7699a589, Hotel@58372a00]
City:Indore with Hotels: [Hotel@4dd8dc3]
City:Mumbai with Hotels: [Hotel@6d03e736, Hotel@568db2f2]
City:Sehore with Hotels: [Hotel@378bf509]
Desired output I want:
City:Ujjain with Hotels: [H5]
City:Pune with Hotels: [H1, H3, H8]
City:Indore with Hotels: [H6]
City:Mumbai with Hotels: [H4]
City:Sehore with Hotels: [H7]
Please help. I have a requirement where I don't want to alter bean class by overriding equals, hashcode and tostring method. Overriding these method would have been simpler to resolve this issue but looking for alternatives.