** Technology introduced from Java SE 8 **
Lambda expressions allow you to write multithreaded programs with multiple processor cores in today's computers with significantly simpler code than ever before.
Quote Java programming is so simple with lambda expressions and stream APIs! --Why you should move to Java SE 8 now https://builder.japan.zdnet.com/sp_oracle/35065645/
Using a lambda expression seems to make coding simple.
For the time being, I feel like I can definitely use it when I can use a lambda expression.
Suppose the list contains the following data:
From this data, people aged 40 and over are extracted and output in ascending order of age. Suppose you write a program called.
List<Musician> users = Arrays.asList(
new Musician(1, "Oyamada", "Sohei", 34, "Fukuoka Prefecture"),
new Musician(2, "Kishida", "Traditional", 42, "Kyoto"),
new Musician(3, "Mukai", "Hidenori", 45, "Fukuoka Prefecture"),
new Musician(4, "Fujiwara", "Motoo", 39, "Chiba"),)
This is also a quote, but up to Java SE 7
Below for data extraction over 40 years old
Set<Musician> musician = new HashSet<>();
for (Musician user : users) {
if (user.getAge() > 40 ) {
musisian.add(user);
}
}
Below to sort the extracted data
List<Musician> sorted = new ArrayList<>(musician);
Collections.sort(sorted, new Comparator<Musician>() {
public int compare(Musician m1, Musician m2) {
return Integer.compare(m1.getAge(), m2.getAge());
}
})
Below in the output of the sorted data
for (Musician user : sorted) {
System.out.println(user.getFirstName());
}
I will code it like this.
For the processing that you want to realize, you are declaring a new variable that holds the sort result in the intermediate processing.
If you try to parallelize this process, if you declare a variable in the intermediate process, synchronous processing will be required, performance will decrease, and parallelization will become more difficult to achieve.
The maintainability of the code is also not very good.
While the essential processing is extraction, sorting, and result output, there are many intermediate processing.
** So Java SE 8 **
users.Stream()
.filter(u -> u.getAge() > 40)
.sorted((m1, m2) -> Integer.compare(m1.getAge(), m2.getAge()))
.forEach(user -> System.out.println(user.getFirstName()));
You can code simply and overwhelmingly sensuously.
You can easily realize parallel processing! That guy
users.parallelStream()
.filter(u -> u.getAge() > 40)
.sorted((m1, m2) -> Integer.compare(m1.getAge(), m2.getAge()))
.sequential()
.forEach(user -> System.out.println(user.getFirstName()));
users.parallelStream()
You can easily implement parallel processing just by adding.
By the way, the following
.sequential()
Means that output processing is not processed in parallel.
The above is a summary that also serves as a reminder.
Recommended Posts