java8 .stream().map().collect() usage

mylist.stream()
    .map(myfunction->{
        return item;
    }).collect(Collectors.toList());

Description:
steam() : Convert a source data, which can be a collection, array, I/O channel, generator, etc., into a stream.

forEach() : Iterate over each data in the stream. The following code snippet uses forEach to output 10 random numbers.

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

map() : Used to map each element to the corresponding result. The following code snippet uses map to output the square number corresponding to the element:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

filter() : The filter method is used to filter out elements based on the set conditions. The following code snippet uses the filter method to filter out empty strings:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
int count = strings.stream().filter(string -> string.isEmpty()).count();
limit
limit 方法用于获取指定数量的流。 以下代码片段使用 limit 方法打印出 10 条数据:

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

sorted() : Used to sort the stream. The following code snippet uses the sorted method to sort the output 10 random numbers:

Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
并行(parallel)程序
parallelStream 是流并行处理程序的代替方法。以下实例我们使用 parallelStream 来输出空字符串的数量:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
int count = strings.parallelStream().filter(string -> string.isEmpty()).count();
我们可以很容易的在顺序运行和并行直接切换。

Collectors() : The class implements many reduction operations, such as converting streams into collections and aggregating elements. Collectors can be used to return lists or strings:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
 
System.out.println("筛选列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);

Guess you like

Origin blog.csdn.net/xulong5000/article/details/108361779