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. Create a class named BasicPerson. This class will have a String attribute named name and a long attribute named age. Create the methods to get and set the value of both the attributes. As the source code of this class is very simple, it won't be included here.
  3. Create another auxiliary class named FileGenerator. This class will have a method named generateFile() that receives the number of lines in the simulated file and returns its content as a List of String:
        public class FileGenerator { 
public static List<String> generateFile(int size) {
List<String> file=new ArrayList<>();
for (int i=0; i<size; i++) {
file.add("Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Morbi lobortis
cursus venenatis. Mauris tempus elit ut
malesuada luctus. Interdum et malesuada fames
ac ante ipsum primis in faucibus. Phasellus
laoreet sapien eu pulvinar rhoncus. Integer vel
ultricies leo. Donec vel sagittis nibh.
Maecenas eu quam non est hendrerit pu");
}
return file;
}
}
  1. Then, create the Main class with the main() method. First, create a list of random Person objects using the PersonGenerator class:
        public class Main { 

public static void main(String[] args) {

// Create list of persons
List<Person> persons = PersonGenerator.generatePersonList(100);
  1. Then, we'll use the mapToDouble() method to convert the stream of Person objects into DoubleStream of double values. Create a parallel stream using the parallelStream() method and then use the mapToDouble() method, passing as parameter a lambda expression that receives a Person object and returns its salary, which is a double number. Then use the distinct() method to get the unique values and the forEach() method to write them to the console. We also get the number of different elements written using the count() method:
        DoubleStream ds = persons.parallelStream().mapToDouble
(p -> p.getSalary());
ds.distinct().forEach(d -> {
System.out.printf("Salary: %f ", d);
});
ds = persons.parallelStream().mapToDouble(p -> p.getSalary());
long size = ds.distinct().count();
System.out.printf("Size: %d ", size);
  1. Now, we'll transform the Person objects of the stream into BasicPerson objects. Create the stream using the parallelStream() method and use the map() method to transform the objects. This method receives as parameter a lambda expression that receives a Person object, creates a new BasicPerson object, and establishes the value of its attributes. Then, we write the values of the attributes of the BasicPerson object using the forEach() method:
        List<BasicPerson> basicPersons = persons.parallelStream().map
(p -> {
BasicPerson bp = new BasicPerson();
bp.setName(p.getFirstName() + " " + p.getLastName());
bp.setAge(getAge(p.getBirthDate()));
return bp;
}).collect(Collectors.toList());

basicPersons.forEach(bp -> {
System.out.printf("%s: %d ", bp.getName(), bp.getAge());
});
  1. Finally, we'll learn how to manage the situations where an intermediate operation returns Stream. In this case, we'll work with a  Stream of streams, but we can concatenate all these Stream objects into a unique Stream using the flatMap() method. Generate List<String> with 100 elements using the FileGenerator class. Then, create a parallel stream with the parallelStream() method. We'll split each line to get its words using the split() method, and with the of() method of the Stream class, we convert the resultant Array into Stream. If we use the map() method, we are generating a Stream of streams, but using the flatMap() method we'll get a unique Stream of String objects with all the words of the whole List. Then, we get the words with a length greater than zero with the filter() method, sort the stream with the sorted() method, and collect it to Map using the groupingByConcurrent() method where the keys are the words and the values are the number of times each word appears in the stream:
        List<String> file = FileGenerator.generateFile(100); 
Map<String, Long> wordCount = file.parallelStream()
.flatMap(line -> Stream.of(line.split("[ ,.]")))
.filter(w -> w.length() > 0).sorted()
.collect(Collectors.groupingByConcurrent(e -> e, Collectors
.counting()));

wordCount.forEach((k, v) -> {
System.out.printf("%s: %d ", k, v);
});
  1. Finally, we have to implement the getAge() method used previously in the code. This method receives the date of birth of a Person object and returns its age:
        private static long getAge(Date birthDate) { 
LocalDate start = birthDate.toInstant()
.atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate now = LocalDate.now();
long ret = ChronoUnit.YEARS.between(start, now);
return ret;
}
..................Content has been hidden....................

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