Java 8:使用 lambda 表达式修改流中的特定元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42221300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:27:59  来源:igfitidea点击:

Java 8: modify specific element in the stream by using lambda expressions

javalambdajava-8java-stream

提问by Andi Pavllo

I need to modify a list on int as it follows:

我需要修改 int 上的列表,如下所示:

  • Every element == 10 needs to be doubled
  • 每个元素 == 10 都需要加倍

Here is my attempt:

这是我的尝试:

list.stream()
            .filter(val -> val.getValue() == 10)
            .map(val -> {
                val.doubleValue();
                return val;
            })
            .forEach(System.out::println);

The problem is that I'm filtering the elements, while I would like to keep them all and just modify the ones == 0.

问题是我正在过滤元素,而我想保留所有元素并且只修改那些 == 0。

EDIT: the list is composed of elements of MyType, defined as it follows:

编辑:列表由 的元素组成MyType,定义如下:

public class MyType {

    private int val;

    public MyType(int v){
        this.val = v;
    }

    public void doubleVal(){
        val*val;
    }

    public int getValue(){
        return val;
    }
}

Any suggestion?

有什么建议吗?

回答by Eran

Don't use filter. Put all the logic in map:

不要使用filter. 把所有的逻辑放在map

list.stream()
    .map(val -> val == 10 ? 2*val : val)
    .forEach(System.out::println);

EDIT : I simplified the code after your clarification that the elements of the list are Integers. Note that the original Listremains unchanged.

编辑:在您澄清列表的元素是Integers之后,我简化了代码。请注意,原始文件List保持不变。

回答by Sekar

Evaluate the condition in map instead of filter.

评估地图而不是过滤器中的条件。

List<Integer> list = new ArrayList<>();

    list.add(10);
    list.add(5);
    list.add(4);

    list.stream().map(val -> {
        if(val < 10){
            return val * val;
        }
        return val;
    }).forEach(System.out::println);

This gives out as 10, 25 and 16;

这给出为 10, 25 and 16;

回答by Redlab

Assuming that your list is a list of Val, and Val is something like

假设您的列表是 Val 的列表,而 Val 类似于

class Val {
  private int v;

  public Val(int v) {
    this.v = v;
  }
  int getValue() {
    return v;
  }

  public void doubleValue() {
    v *= 2;
  }
}

then

然后

  public static void main(String ... args ) {
        List<Val> ints = Arrays.asList(new Val(1), new Val(5), new Val(10), new Val(2));
        ints.stream().map((v) -> {
            if (v.getValue() == 10) v.doubleValue(); return v;
        }).forEach(v -> System.out.println(v.getValue()));

    }

will do the trick.

会做的伎俩。