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

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);
主站蜘蛛池模板: 昌吉市| 绥芬河市| 南乐县| 兴和县| 柘城县| 荆门市| 沽源县| 乐东| 客服| 鲁甸县| 平凉市| 烟台市| 汶川县| 忻州市| 乌什县| 沁水县| 济宁市| 安阳市| 武清区| 尼木县| 华安县| 亳州市| 江北区| 琼结县| 新津县| 石家庄市| 天津市| 高邮市| 山西省| 大田县| 永寿县| 丽江市| 调兵山市| 哈巴河县| 友谊县| 小金县| 遵义县| 九龙坡区| 土默特左旗| 盐池县| 简阳市|