简体   繁体   English

用Java获取和修改集合中的对象

[英]Fetching and modifying an object in a set in Java

I have MyFinalSalad class consisting of the following elements: 我的MyFinalSalad类包含以下元素:

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. 我已经equals实现,如2个MyFinalSalad对象是相等的,如果他们有相同的AppleClassBananaClassPearClass在他们的对象。

Now, I am creating a set of MyFinalSalad objects. 现在,我正在创建一set MyFinalSalad对象。

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 . 总之,如果mySalad已经存在于mySet中,添加spice对象名单spicesmySaladmySet ,否则添加mySaladmySet创建一个新的香料后list ,加入cinnamon它并插入列表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? 我的问题是,如果set已经具有mySalad并且我想在该对象的列表中添加新的香料,该如何实现?

From https://stackoverflow.com/a/7283419/887235 I have the following: https://stackoverflow.com/a/7283419/887235获得以下信息:

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. 我在想, if已经执行了contains检查,则将永远不会遇到orElse(null) ,因为我已经输入了。 Thus null.getSpices() will never occur. 因此null.getSpices()将永远不会发生。 Is this assumption correct? 这个假设正确吗?

Is there a better way to do it? 有更好的方法吗?

I cannot change Set to Map . 我无法将“ SetMap更改为。

Your assumption is correct. 您的假设是正确的。 The orElse(null) will never take place since you check if the set contains the salad right before. orElse(null)永远不会发生,因为您检查集合contains是否contains沙拉。 You could replace it with get() . 您可以将其替换为get()

However, I would also go one level before and handle it as an Optional, taking the advantage of isPresent and get method. 但是,我也要先使用isPresentget方法, isPresent其作为Optional进行处理。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM