官术网_书友最值得收藏!

Working with intermediate operations

Following are some of the frequently used intermediate operations:

  1. filter(): The method filter() method creates a new stream by first evaluating each element in the stream that passes a certain criteria that matches a given predicate:
//Filter Operation
IntStream.rangeClosed(1, 10)
.filter(s -> s>4)
.forEach(p -> System.out.println(p));
  1. map(): A map() is an intermediate operation that produces an equal number of output values as there are input values. It is a unary operator that simply transforms the element so each time an element is passed to the map function it returns an object and hence there is a one-to-one mapping between the input values and the transformed output values. Map is usually required when we want to transform the elements of the stream, for example we want to create a stream of integers corresponding to the length of each string in the input stream. Such transformation can be achieved by using map():
int sumOfLength=streamSupplier.get().map(x ->x.toString().length()).peek(x->System.out.println(Integer.parseInt(x.toString())))

.mapToInt(x->x.intValue()).sum();

As you may notice, we have also used special map() functions, such as mapToInt(), corresponding to primitive data types such as int, long, and double. The purpose of these special map() functions is to provide some added pipeline operations, such as sum().

  1. flatmap(): flatMap() is a combination of two operations, the map() and flat() operations. When the data is passed to flatMap() it may return more than one value to flatten the result. A simple corollary can be drawn from the following representation:

Hence, flatMap() essentially takes an input element and transforms it in such a way that it may result in returning more than one value so that the resultant output is of the form Stream<T>:

//flatMap Example
Stream<List<String>>streamList = Stream.of(
Arrays.asList("FistList-FirstElement"),
Arrays.asList("SecondList-FirstElement", "SecondList-SecondElement"),
Arrays.asList("ThirdList-FirstElement"));
//The streamList is of the form List<String>
Stream<String>flatStream = streamList
.flatMap(strList ->strList.stream());
// But after applying flatMap operaton it translates into Strem<String>
flatStream.forEach(System.out::println);

Similar to the map() operation, even the flatMap() operation has primitive variants of flatMap() functions to specially cater to int, long, and double data types.

  1. Sorted: The elements of a stream can be sorted in their natural order by using the sorted() method. However, the element of the streams must be comparable or else ClassCastException is thrown:
//Natural Sorting
streamSupplier.get().sorted().forEach(System.out::println);

Apart from natural sorting, custom sorting of elements is also possible, where an overridden method of the sorted() method accepting a compartor can be used. If we want to change the natural sorting to reverse the order it can be achieved by:

//Comparing elements with reverse order
streamSupplier.get().sorted(Comparator.reverseOrder()).forEach(System.out::println);

Another way of sorting data is to use a Lambda function as an argument to the comparator:

//Sorting the element in reverse order based on their length streamSupplier.get().sorted(Comparator.comparing(x ->x.toString().length()).reversed()).forEach(System.out::println);

Sorting on multiple fields is also possible as sorting algorithms can be chained to sort data in a specific sequence:

//Sorting on multiple fields
streamSupplier.get().sorted(Comparator.comparing(x ->x.toString().length()).thenComparing(x->x.toString())).forEach(System.out::println);
  1. Distinct: The distinct() method returns the unique values of the elements in the stream. The comparison property can be altered by using the overridden equals method:
//Distinct filters all the multiple records having same length streamSupplier.get().mapToInt(x->x.toString().length()).distinct().forEach(System.out::println);
  1. Limit: In certain scenarios particularly in the case of infinite streams, the stream can be truncated using the limit() method with the appropriate value of maxSize:
//Limiting the size of the stream streamSupplier.get().limit(2).forEach(System.out::println);
主站蜘蛛池模板: 名山县| 克什克腾旗| 长泰县| 定西市| 彰化县| 双柏县| 平邑县| 六枝特区| 广西| 晋中市| 桑植县| 宁都县| 汶上县| 长顺县| 顺平县| 上杭县| 京山县| 五家渠市| 常熟市| 邳州市| 临武县| 昌都县| 神农架林区| 闻喜县| 南部县| 丰原市| 蕉岭县| 乐业县| 枝江市| 桦南县| 博野县| 灵山县| 临沂市| 泸水县| 涞水县| 长垣县| 双柏县| 陵川县| 九江县| 陆河县| 盐源县|