0

I have MyFinalSalad class consisting of the following elements:

AppleClass apple;
BananaClass banana;
PearClass pear;
List<SpicesClass> spices;

I have equals implemented such as 2 MyFinalSalad objects are equal, if they have same AppleClass, BananaClass, PearClass objects in them.

Now, I am creating a set of MyFinalSalad objects.

And I have the following code:

MyFinalSalad mySalad = new MyFinalSalad(apple, banana, pear);
SpiceClass cinnamon = new SpiceClass("cinnamon");
if (mySet.contains(mySalad)) {
    // I want to fetch mySalad object in the set and add cinnamon to the list of spices
} else {
  List<SpiceClass> spices = new ArrayList<>();
  spices.add(cinnamon);
  mySalad.setSpices(spices);
  mySet.add(mySalad);
}

To summarize, if mySalad is already present in mySet, add the spice object to the list of spices in mySalad from mySet, else add mySalad to mySet after creating a new spice list, adding cinnamon to it and inserting list in mySalad.

My question is, if set already has mySalad and I want to add a new spice to the list in that object, how do I achieve it?

From https://stackoverflow.com/a/7283419/887235 I have the following:

mySet.stream().filter(mySalad::equals).findAny().orElse(null).getSpices().add(cinnamon);

Is this the only way or the right way to do it? Or is there a better way?

I was thinking that as I am already entering if after doing a contains check, orElse(null) will never be encountered. Thus null.getSpices() will never occur. Is this assumption correct?

Is there a better way to do it?

I cannot change Set to Map.

Vicky
  • 16,679
  • 54
  • 139
  • 232
  • As mentioned in the same thread if your thread is NavigableSet you can retrive simply by `Foo bar = set.floor(foo); ` Then do your operation https://stackoverflow.com/a/25393190/1423818 – mallikarjun Sep 16 '19 at 10:27

1 Answers1

0

Your assumption is correct. The orElse(null) will never take place since you check if the set contains the salad right before. You could replace it with get().

However, I would also go one level before and handle it as an Optional, taking the advantage of isPresent and get method.

Salad mySalad = new Salad();
Optional<Salad> possibleSalad = set.stream().filter(mySalad::equals).findAny();
if (possibleSalad.isPresent()) {
    Salad alreadyExistingSalad = possibleSalad.get();
    // combine spices
} else {
    // add new salad
}
George Z.
  • 6,643
  • 4
  • 27
  • 47