Amit-Chavda
Amit-Chavda

Reputation: 45

How to convert a list of objects containing other objects into HashMap

hope you are doing well.

I have some list of other object which again contains two different objects. I have tried couple of ways using Collectors.groupingBy() but didn't get expected output. So help me to figure out solution to this.

Suppose I following three entities:

class FruitFlower {
    Fruit fruit;
    Flower flower;
}

class Fruit {
    String name;
}

class Flower {
    String name;
}

And I have a list like this

 List<FruitFlower> fruitFlowers = new ArrayList<>();
        fruitFlowers.addAll(
                new FruitFlower(
                        new Fruit("Apple"),
                        new Flower("Rose")
                ),
                new FruitFlower(
                        new Fruit("Banana"),
                        new Flower("Lily")
                ),
                new FruitFlower(
                        new Fruit("Apple"),
                        new Flower("Sunflower")
                ),
                new FruitFlower(
                        new Fruit("Banana"),
                        new Flower("Purple")
                ),
                new FruitFlower(
                        new Fruit("Banana"),
                        new Flower("Rose")
                )
        );

Now, I want to order this list by some filter such that it returns HashMap like this

        HashMap<Fruit,List<Flower>> hashMap=new HashMap<>();

Resultant Object:
{
     "Apple":["Rose","Sunflower"]
      "Banana":["Lily","Purple","Rose"]
}

Where

Expected output is a HadhMap that contains only unique values and a list of other values connected to that particular object. You can consider Objects of String for simplicity.

This is Java question and expected answer should be in Java 8 using stream API.

Thank you in advance.

Upvotes: 0

Views: 121

Answers (1)

BambooleanLogic
BambooleanLogic

Reputation: 8171

As you suspected, groupingBy is the right approach.

fruitFlowers.stream().collect(Collectors.groupingBy(
    i -> i.fruit,
    Collectors.mapping(i -> i.flower, Collectors.toList())
));

The first parameter to groupingBy defines how you want to group them. In this case, we want to group by fruits.

The second parameter describes what the value of the resulting map should be. In this case, we want the values to be the list of flowers.

Note that this approach only works if groupingBy can deduce that two fruits are equivalent. This requires that the Fruit class contains an appropriate implementation of equals and hashCode.

If the Fruit class cannot be extended to add those methods, one can change the first lambda to i -> i.fruit.name, but that would make the resulting Map to have String keys instead of Fruit.

Upvotes: 1

Related Questions