Java Stream functional programming Part III: Results process stream conduit

A, Java Stream pipeline data processing operations

In the prior written this article in number, had given you before Java Stream pipeline flow is used to simplify the java API collections element being processed. Divided into three stages during use. Before starting this article, I think it still needs some new friends to introduce these three stages, as shown:

Java Stream functional programming?  Used say good, case Detailed graphics to give you

  • The first phase (shown in blue): The collection array, or line of the text file is converted to java Stream flow duct
  • The second stage (dashed line in the figure): streaming data pipeline processing operations, each processing element in the pipeline. Output elements on a pipe as an input element of the next pipe.
  • Third stage (shown in green): results of the processing operation pipeline flow, i.e. the core to be described herein.

Before getting started, there is still a need to look back to our previous example we talked about:


List<String> nameStrs = Arrays.asList("Monkey", "Lion", "Giraffe","Lemur");

List<String> list = nameStrs.stream()
        .filter(s -> s.startsWith("L"))
        .map(String::toUpperCase)
        .sorted()
        .collect(toList());
System.out.println(list);
  • First, using the stream () method to convert a string for the pipeline flow Stream List
  • Then piping the data processing operation, all strings beginning with a capital L fliter function filtered first, then the string is converted to uppercase letters pipe the toUpperCase, and then call the sorted ranking method. Usage of the API in the previous article of this number have introduced. Which used to lambda expressions and function reference.
  • Finally, the collect function result processing, the pipeline streams into a java Stream List. The final list of output results are:[LEMUR, LION]

If you do not use java Stream pipeline flow, then think about how many lines of code you need to complete the above functions? Back to the topic, this article is to give you about the third phase: the pipeline stream processing results can be what does it do? Let's start now!

Two, ForEach and ForEachOrdered

If we just hope the results will be printed Stream pipeline flow, rather than the type of conversion, we can use the forEach () method or forEachOrdered () method.


Stream.of("Monkey", "Lion", "Giraffe", "Lemur", "Lion")
        .parallel()
        .forEach(System.out::println);
Stream.of("Monkey", "Lion", "Giraffe", "Lemur", "Lion")
        .parallel()
        .forEachOrdered(System.out::println);
  • Parallel () function is represented in the pipeline processing elements in parallel, rather than serial processing, so that faster processing speed. But this is likely to lead to the elements behind the first stream processing pipeline, after the previous element processing, which is the order of the elements can not be guaranteed
  • forEachOrdered can understand from the name of point of view, although it may not be guaranteed in the data processing sequence, but forEachOrdered way to guarantee consistent with the order of the elements into the pipeline flow in the order of the elements output. That is like the following (forEach method is not guaranteed in this order):
Monkey
Lion
Giraffe
Lemur
Lion

Third, collect collect elements

The most common use is java Stream: the collection classes converted into a flow conduit, two data processing pipeline flow, the pipe flow three processing result is converted into a set of classes. Then collect () method provides such functions for us: the duct flow processing result is converted into a set of classes.

3.1 The collection is Set

Stream processing result collected by Collectors.toSet () method, all of the elements collected into the collection Set.


Set<String> collectToSet = Stream.of(
   "Monkey", "Lion", "Giraffe", "Lemur", "Lion"
) 
.collect(Collectors.toSet());

//最终collectToSet 中的元素是:[Monkey, Lion, Giraffe, Lemur],注意Set会去重。

3.2. Collect List

Similarly, elements may be collected Listusing the toList()collector.


List<String> collectToList = Stream.of(
   "Monkey", "Lion", "Giraffe", "Lemur", "Lion"
).collect(Collectors.toList());

// 最终collectToList中的元素是: [Monkey, Lion, Giraffe, Lemur, Lion]

3.3. General collection methods

The above elements collection methods to introduce, are private. Such as using Collectors.toSet () Set type collected as a set; use Collectors.toList () List type of collection set. So, there is no element of a more general data collection mode, data collection interface sub Collection of any type.
So, here we introduce as a common element collection methods, you can collect data element to any type of Collection: namely the way you want to provide a constructor Collection type.


LinkedList<String> collectToCollection = Stream.of(
   "Monkey", "Lion", "Giraffe", "Lemur", "Lion"
).collect(Collectors.toCollection(LinkedList::new));

//最终collectToCollection中的元素是: [Monkey, Lion, Giraffe, Lemur, Lion]

Note: The code used in the LinkedList :: new, actually calling the constructor LinkedList will collect elements to the Linked List. Of course, you can also use such LinkedHashSet::newand PriorityQueue::newthe data elements collected for other types of collections, so the more generic.

3.4. Array collected

Stream processing result collected by toArray (String [] :: new) method, all of the elements collected into a string array.


String[] toArray = Stream.of(
   "Monkey", "Lion", "Giraffe", "Lemur", "Lion"
) .toArray(String[]::new);

//最终toArray字符串数组中的元素是: [Monkey, Lion, Giraffe, Lemur, Lion]

3.5. Collected Map

Use Collectors.toMap () method of the data elements collected Map inside, but there is a problem: that is in the pipeline as an element key, or as a value. We use a Function.identity () method, which was simply to return to a "t -> t" (lambda expression input is output). Further flow pipe handler using distinct()uniqueness of the key to ensure Map.


Map<String, Integer> toMap = Stream.of(
    "Monkey", "Lion", "Giraffe", "Lemur", "Lion"
)
.distinct()
.collect(Collectors.toMap(
       Function.identity(),   //元素输入就是输出,作为key
       s -> (int) s.chars().distinct().count()// 输入元素的不同的字母个数,作为value
));

// 最终toMap的结果是: {Monkey=6, Lion=4, Lemur=5, Giraffe=6}   

3.6. Packet collect groupingBy

Collectors.groupingBy packets used to implement the elements of the collection, the following code shows how to collect data according to the first letter of the different elements of different List, and packaged as Map.


Map<Character, List<String>> groupingByList =  Stream.of(
    "Monkey", "Lion", "Giraffe", "Lemur", "Lion"
)
.collect(Collectors.groupingBy(
       s -> s.charAt(0) ,  //根据元素首字母分组,相同的在一组
       // counting()        // 加上这一行代码可以实现分组统计
));

// 最终groupingByList内的元素: {G=[Giraffe], L=[Lion, Lemur, Lion], M=[Monkey]}
//如果加上counting() ,结果是:  {G=1, L=3, M=1}

Fourth, other commonly used methods


boolean containsTwo = IntStream.of(1, 2, 3).anyMatch(i -> i == 2);
// 判断管道中是否包含2,结果是: true

long nrOfAnimals = Stream.of(
    "Monkey", "Lion", "Giraffe", "Lemur"
).count();
// 管道中元素数据总计结果nrOfAnimals: 4


int sum = IntStream.of(1, 2, 3).sum();
// 管道中元素数据累加结果sum: 6


OptionalDouble average = IntStream.of(1, 2, 3).average();
//管道中元素数据平均值average: OptionalDouble[2.0]



int max = IntStream.of(1, 2, 3).max().orElse(0);
//管道中元素数据最大值max: 3



IntSummaryStatistics statistics = IntStream.of(1, 2, 3).summaryStatistics();
// 全面的统计结果statistics: IntSummaryStatistics{count=3, sum=6, min=1, average=2.000000, max=3}

Look forward to your attention

Guess you like

Origin www.cnblogs.com/zimug/p/11839517.html