mardi 21 avril 2020

Java functional programming random int stream math abs not working

I have the following code:

import java.util.Random;
import java.util.stream.Stream;

public class StreamIntReduce
{
    public static void main(String[] args)
    {
        Stream.generate(() -> new Random().nextInt())
                .limit(100000)
                .map(x -> Math.abs(x))
                .reduce((a,b) -> {
                    System.out.println(a);
                    System.out.println(b);
                    return a + b;
                })
                .ifPresent(System.out::println);
    }
}

I use .map(x -> Math.abs(x)) to convert negative numbers to positive. Why is it that my output System.out.println(a); and System.out.println(b); still contains negative numbers?

-1293102468
2036920025
743817557
939157978
1682975535
1444066960
-1167924801
1361593362
193668561
1764534904
1958203465
739693193
-1597070638



Aucun commentaire:

Enregistrer un commentaire