How to do it...

Follow these steps to implement the example:

  1. First, we'll implement some auxiliary classes we will use in the example. First, implement the Person class, which stores the basic attributes of a person, and the PersonGenerator class, which generates a List of random Person objects. Please, check the recipe Apply an action to all the elements of a stream to see the source code of both the classes.
  2. Now, implement the Main class with the main() method. First, we'll create an Array of int numbers. Then, we'll create a parallel stream with the parallelStream() method from this array, use the sorted() method to sort the elements of the array, and use the forEachOrdered() method to write the elements in an ordered way. Take into account that this operation won't use all the power of our multi-core processor as it has to write the elements in the specified order:
        public class Main { 
public static void main(String args[]) {
int[] numbers={9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9};
Arrays.stream(numbers).parallel().sorted().forEachOrdered
(n -> {
System.out.printf("%d ", n);
});
  1. Now, let's try the same principles with a Stream of Person objects. Create a list of 10 random Person objects using the PersonGenerator class and use the same methods, sorted() and forEachOrdered(), to see how the persons are written in an ordered way:
        List<Person> persons=PersonGenerator.generatePersonList(10); 
persons.parallelStream().sorted().forEachOrdered(p -> {
System.out.printf("%s, %s ",p.getLastName(),p.getFirstName());
});
  1. Finally, we'll see how to eliminate the encounter order of a data structure using the unordered() method. First, we'll create TreeSet from our List of random Person objects. We use TreeSet because it orders the elements internally. Then, we make a loop to repeat the operations ten times and see how there's a difference between the ordered and the unordered operations:
        TreeSet<Person> personSet=new TreeSet<>(persons); 
for (int i=0; i<10; i++) {
  1. Then, we create a stream from PersonSet using the stream() method, convert it to parallel with the parallel() method, get the first element with the limit() method, and return the Person object, collecting it to a list and getting the first element:
        Person person= personSet.stream().parallel().limit(1)
.collect(Collectors.toList()).get(0);
System.out.printf("%s %s ", person.getFirstName(),
person.getLastName());
  1. Now, we perform the same operation but remove the ordered constraint with the unordered() method between the stream() and parallel() methods:
        person=personSet.stream().unordered().parallel().limit(1)
.collect(Collectors.toList()).get(0);
System.out.printf("%s %s ", person.getFirstName(),
person.getLastName());
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.180.43