Java Lambda, Stream and Filter

huangapple go评论158阅读模式
英文:

Java Lambda, Stream and Filter

问题

创建一个新的数组,在其中所有小于3的元素将变为负数,而大于或等于3的元素将保持不变。如果没有元素小于3,那么就会抛出一个错误。所以在这种情况下,新数组将是[-1, -2, 3, 4, 5]。

如何使用lambda和filter来完成这个任务?

这是我的代码片段:

AtomicInteger a = new AtomicInteger(0);

arrayList.stream()
    .map(data -> {
      if(data < 3) {a.getAndIncrement(); return -1 * data;}
      return data;
    })
    .collect(Collectors.toList());

if(a.get() == 0) {
  throw new RuntimeException();
}
英文:

I have an array [ 1,2,3,4,5 ] and wanted to do something like this.

Create a new array where all elements below 3 will become negative and all elements above and equal to 3 will remain the same. if there is no element below 3 then it that case I have to throw an error.

So in this case new array will be [ -1, -2, 3, 4, 5].

How this can be done using lambda, filter?

This is my piece of code

AtomicInteger a = new AtomicInteger(0);

arrayList.stream()
    .map(data -&gt; {
      if(data &lt; 3) {a.getAndIncrement(); return -1 * data;}
      return data;
    })
    .collect(Collectors.toList());

if(a.get() == 0) {
  throw  new RuntimeException();
}

答案1

得分: 0

这种做法可以满足您的需求。

List<Integer> mappingResult = Stream.of(1, 2, 3, 4, 5)
    .map(v -> v < 3 ? -v : v)
    .collect(Collectors.toList());
mappingResult.stream().filter(v -> v < 3).findAny().orElseThrow(() -> new InvalidStateException("No elements less than 3"));

或者这个:

AtomicBoolean b = new AtomicBoolean();
List<Integer> mappingResult = Stream.of(1, 2, 3, 4, 5)
    .map(v -> v < 3 ? -v : v)
    .peek(v -> { if (v < 3) b.set(true); })
    .collect(Collectors.toList());
if (!b.get()) {
    throw new InvalidStateException("No elements less than 3");
}

如果您希望负数仍然保持负数,可以使用以下方式:

.map(v -> v > 0 && v < 3 ? -v : v)

正如注释所说,您甚至可以进一步改进它(我假设注释与原始要求一致):

AtomicBoolean b = new AtomicBoolean();
List<Integer> mappingResult = Stream.of(1, 2, 3, 4, 5)
    .map(v -> {
        if (v > 0 && v < 3) {
            b.set(true);
            return -v;
        }
        return v;
    }).collect(Collectors.toList());
if (!b.get()) {
    throw new InvalidStateException("No elements less than 3");
}
英文:

This kind of does what you require

    List&lt;Integer&gt; mappingResult = Stream.of(1, 2, 3, 4, 5)
                                        .map(v -&gt; v &lt; 3 ? -v : v)
                                        .collect(Collectors.toList());
    mappingResult.stream().filter(v -&gt; v &lt; 3).findAny().orElseThrow(() -&gt; new InvalidStateException(&quot;No elements less than 3&quot;));

Or this

    AtomicBoolean b=new AtomicBoolean();
    List&lt;Integer&gt; mappingResult = Stream.of(1, 2, 3, 4, 5)
                                        .map(v -&gt; v &lt; 3 ? -v : v)
                                        .peek(v-&gt; {if(v&lt;3) b.set(true);})
                                        .collect(Collectors.toList());
    if(!b.get()){
        throw new InvalidStateException(&quot;No elements less than 3&quot;);
    }

If you want negatives to still be negatives, use

.map(v -&gt; v&gt;0 &amp;&amp; v &lt; 3 ? -v : v)

As comment says, you can improve that even further (I assume that comments are aligned with original requirements)

    AtomicBoolean b = new AtomicBoolean();
    List&lt;Integer&gt; mappingResult = Stream.of(1, 2, 3, 4, 5)
                                        .map(v -&gt; {
                                            if (v &gt; 0 &amp;&amp; v &lt; 3) {
                                                b.set(true);
                                                return -v;
                                            }
                                            return v;
                                        }).collect(Collectors.toList());
    if (!b.get()) {
        throw new InvalidStateException(&quot;No elements less than 3&quot;);
    }

答案2

得分: 0

你应该比较 inputoutput。如果它们相等,抛出一个异常。

List<Integer> input = List.of(1, 2, 3, 4, 5);
List<Integer> output = input.stream()
    .map(data -> data < 3 ? -data : data)
    .collect(Collectors.toList());
if (output.equals(input))
    throw new RuntimeException();
英文:

You should compare input and output. If they are equal, throw an exception.

List&lt;Integer&gt; input = List.of(1, 2, 3, 4, 5);
List&lt;Integer&gt; output = input.stream()
    .map(data -&gt; data &lt; 3 ? -data : data)
    .collect(Collectors.toList());
if (output.equals(input))
    throw new RuntimeException();

huangapple
  • 本文由 发表于 2020年8月13日 16:16:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63390920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定