java—spring boot索引中列表元素的总和

icnyk63a  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(342)

**结束。**此问题不符合堆栈溢出准则。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

三个月前关门了。
改进这个问题
SpringBoot中是否有任何库或依赖项可以通过相同的属性获取列表元素的总和?
例如:

public Entity(){
   int index; // common attribute
   int value;
}

Entity entity1 = new Entity(1,2);
Entity entity2 = new Entity(2,3);
Entity entity3 = new Entity(3,3);

Entity entity4 = new Entity(1,5);
Entity entity5 = new Entity(2,9);
Entity entity6 = new Entity(3,9);

Entity entity7 = new Entity(1,5);
Entity entity8 = new Entity(2,1);
Entity entity9 = new Entity(3,7);

List<Entity> list = Arrays.asList(entity1 ,entity2 ,entity3 , ..... );

List<Entity> result = { Entity(1,12), Entity(2,13), Entity(3,10) }
4nkexdtk

4nkexdtk1#

streamapi应用于按属性分组,并使用中的特殊方法计算总和 Entityvalue 领域。
也是一个复制构造函数,getter for index 现场和 toString 需要实现的方法:

// class Entity
// all-args constructor
public Entity(int index, int value) {
    this.index = index;
    this.value = value;
}

// copy constructor
public Entity(Entity other) {
    this.index = other.index;
    this.value = other.value;
}

public Entity merge(Entity other) {
    this.value += other.value;
    return this;
}

public int getIndex() { return this.index; }

@Override
public String toString() {
    return "Entity (" + index + ", " + value + ")";
}
// assuming `list` is set as shown above
Collection<Entity> summed = list
        .stream()
        .collect(
            Collectors.toMap(
                Entity::getIndex, // use index as key via reference to the getter method
                Entity::new,      // use copy constructor 
                Entity::merge     // merge values in entity
                , LinkedHashMap::new // keep insertion order (optional)
            ) // build Map<Integer, Entity> 
        )
        .values();

List<Entity> result = new ArrayList<>(summed);

System.out.println(result);

输出:

[Entity (1, 12), Entity (2, 13), Entity (3, 19)]
e7arh2l6

e7arh2l62#

也许你可以使用流api…类似

List<Entity> list = ...

List<Entity> result = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
  Entity sumEntity = list.stream()
    .filter(entity -> entity.getIndex() == i)
    .reduce(accEntity, currEntity -> {
      Entity resEntity = new Entity();
      resEntity.setValue(accEntity.getValue() + currEntity.getValue());
      return resEntity;
  }).orElse(null);
  result.add(sumEntity);
}

相关问题