Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does parallelStream() in java 8 guarantee the order?

I'm trying to understand the behavior of parallelStream() in java 8. Here is my sample code.

List<Person> javaProgrammers = new ArrayList<Person>() {
    {
        add(new Person("Elsdon", "Jaycob", "Java programmer", "male", 43, 2000));
        add(new Person("Tamsen", "Brittany", "Java programmer", "female", 33, 1500));
        add(new Person("Floyd", "Donny", "Java programmer", "male", 33, 1800));
        add(new Person("Sindy", "Jonie", "Java programmer", "female", 32, 1600));
        add(new Person("Vere", "Hervey", "Java programmer", "male", 22, 1200));
        add(new Person("Maude", "Jaimie", "Java programmer", "female", 33, 1900));
        add(new Person("Shawn", "Randall", "Java programmer", "male", 33, 2300));
        add(new Person("Jayden", "Corrina", "Java programmer", "female", 33, 1700));
        add(new Person("Palmer", "Dene", "Java programmer", "male", 33, 2000));
        add(new Person("Addison", "Pam", "Java programmer", "female", 34, 1300));
    }
};

System.out.println("Serial:" + javaProgrammers.stream().filter(person -> person.age == 33).findFirst().toString());
System.out.println("Parallel:" + javaProgrammers.parallelStream().filter(person -> person.age == 33).findFirst().toString());

Here I'm comparing stream() and parallelStream(), and I expect Brittany Tamsen to be return always in stream() call because that's the first match. But for parallelStream() I do not expect Brittany Tamsen to be returned always because it can be one of any matches, as I expect it to run in parallel.

But the problem is that it also returns Brittany Tamsen always. So it doesn't look like it runs in parallel.

Am I missing something here?

like image 778
Bee Avatar asked Dec 23 '22 23:12

Bee


1 Answers

In addition to Bohemian's answer, It's important to add that, yes, findFirst() will return the first element matching the predicate, whether the stream is parallel or not, since the stream has an encounter order in this case (being created from a List).

findAny(), on the contrary, is free to return any element matching the predicate (and should thus be preferred if you don't really care about which matching element is returned, since it might allow returning sooner in case of a parallel stream).

like image 154
JB Nizet Avatar answered Dec 28 '22 07:12

JB Nizet