Let's look at the new features of Java stream --Stream

I began to try to use the new features of Java six months ago, what impressed me most is that Stream flow and Optional. Stream which improves the efficiency of perception, so that the code looks very cool.

Why use flow?

Abstract has been explained, in order to improve development efficiency. Flow can help us operate efficiently 集合, help us flow by 流水线way of collection 删减, , 合并, 排序, 修改and eventually returns the element data or statistics we want. 流水线Mean, a number of elements need not wait for all the elements of a step operation to complete before the operation to step down, but the next step operation can be carried out as soon as possible, as if the same assembly line factory, which provides the basis for the efficient operation of flow. There is also a flow 内部迭代concept is to show the for loop iteration hidden, so you can be more convenient 并行开发.

Using streams

ready

Need to do to prepare before using streaming, First two concepts: 中间操作and 终端操作. 中间操作Step by step like element processing workshop ratio after each step process, inside style elements or data structure may change, but it still flows. 终端操作Like the production of finished products, want to make the box into final form visible to the final consumer, this time, it is already a product, no longer flow.

To demonstrate the operation then, several data to simulate the

List<JSONObject> menu = new ArrayList<>();
menu.add(new JSONObject().putOpt("name","宫保鸡丁").putOpt("price","28"));
menu.add(new JSONObject().putOpt("name","鱼香肉丝").putOpt("price","30"));
menu.add(new JSONObject().putOpt("name","肉夹馍").putOpt("price","6"));
menu.add(new JSONObject().putOpt("name","煎饼").putOpt("price","6"));
复制代码

Common intermediate operation

filter

Stream filter should be the most common operating inside the filter name suggests is used to filter data, filter parameters can be a lambda expression.

//比如下面这句话,就是得到所有价格小于10的食物,得到的还是流。
//stream()方法将集合转成流
menu.stream().filter(jsonObject -> jsonObject.getInt("price")<10);
复制代码

distinct, limit and skip

deduplication is distinct, limit intercepts the first few elements, skip skip before the number of elements.

List<Integer> integerList = new ArrayList<>();
integerList.add(1);
integerList.add(1);
integerList.add(2);
integerList.add(3);
integerList.stream()
    .distinct()//经过去重,流还剩1、2、3
    .skip(1)//跳过第一个元素,流中还有2、3
    .limit(1);//截取第一个元素,流中还剩2
复制代码

map

map map above filter is a filter element, the element is to change the map style. For example, we want to know all the names of less than 10 food.

menu.stream()
    .filter(jsonObject -> jsonObject.getInt("price")<10)//此时还是jsonObject
	.map(jsonObject -> jsonObject.getStr("name"));//此时变成了String
复制代码

flatMap

The combined stream may be a plurality of arrays into operation, so that the flow element is not returned, but the particular element itself.

Stream.of(menu,foreignMenu)//此时元素是流 List<Stream>
    .flatMap(x -> x.stream())//此时元素是jsonObject List<jsonObject>
    .map(jsonObject -> jsonObject.getStr("name"))
    .distinct();
复制代码

Common terminal method

allMatch、anyMatch、noneMatch、findFirst和findAny

method meaning
allMatch Check the predicate matches all elements
anyMatch Check the predicate matches at least one element
noneMatch Make sure there are no flow element match the given predicate
findFirst Find the first matching element
findAny The return any element of the current flow
//前三个方法都是返回boolean类型
boolean allMatchBool = menu.stream()
    .allMatch(jsonObject -> jsonObject.getInt("price") < 10);
boolean noneMatchBool = menu.stream()
    .noneMatch(jsonObject -> jsonObject.getInt("price") < 10);
boolean anyMatchBool = menu.stream()
    .anyMatch(jsonObject -> jsonObject.getInt("price") < 10);
复制代码

The above is a method returns a boolean, findFirst, findAny elements are returned.

//关于Optional,先不关心,总之是元素就对了
Optional<JSONObject> first = menu.stream().findFirst();
Optional<JSONObject> any = menu.stream().findAny();

System.out.println(first.get().toString());
System.out.println(any.get().toString());

//输出
//{"price":"28","name":"宫保鸡丁"}
//{"price":"28","name":"宫保鸡丁"}
复制代码

The above two methods, it meets the conditions of the data found on stream ahead of the end. Why is the output of the first element, have to realize there are two methods? Because 并行, findAny parallel in terms of restrictions will be less.

reduce

The very beginning to say, the final return value can be a collection of elements, it can be statistics (or inductive), for example, summing the elements. Suppose we need menuall the food each one how much you want to spend.

Optional<Integer> price = menu.stream()//List<JsonObject>
    .map(jsonObject -> jsonObject.getInt("price"))//先将元素转成数字List<Integer>
    .reduce((x, y) -> x + y);
System.out.println(price.get());
复制代码

max and min

This is easy to understand, is that the maximum and minimum thing. The effect is similar

.reduce(Integer::max)
.reduce(Integer::min)
复制代码

Common Flow Summary

Which are not shown sorted, count this are easy to understand. As to collect the back talk, use more.

Conversion flow

In addition to object flow (Stream), and some types of streams, such as IntStream (to IntStream example, other similar) above summation returns Optional object that can return type Integer direct it?

//使用映射方法mapToInt()就ok了
int price = menu.stream()//Stream
    .mapToInt(jsonObject -> jsonObject.getInt("price"))//IntStream
    .sum();
//类型流转化回对象流,可以使用boxed()
IntStream intStream = menu.stream()
	.mapToInt(jsonObject -> jsonObject.getInt("price"));
Stream<Integer> boxed = intStream.boxed();
//当然了IntStream中有很多int类型操作的方法,就不一一举例了,源码打开一看,见名知意
复制代码

collector

Speaking in front of a common intermediate operation, the return value is the stream, some interrupt operation, or return values are values Optional. Stream do not forget the original intention of the beginning of the collection is to solve operational problems. The final conversion to collect a set of operations using the interrupt, the interface parameters Collector, there are a number of transformation methods.

Converted into a collection

The most commonly used Could toList () This method, and returns the results become List.

List<JSONObject> list = menu.stream()
    .filter(jsonObject -> jsonObject.getInt("price") < 10)
    .collect(Collectors.toList());
//当然还有toSet()等等,触类旁通
复制代码

String concatenation

More commonly, it is the string links. Use joining () method

String s = menu.stream()
    .filter(jsonObject -> jsonObject.getInt("price") < 10)
    .map(jsonObject -> jsonObject.getStr("name"))
    .collect(Collectors.joining(","));
复制代码

Packet

The packet attributes provided using groupingBy (), for convenience of explanation, a variety of food value above a type:

List<JSONObject> menu = new ArrayList<>();
menu.add(new JSONObject().putOpt("name","宫保鸡丁").putOpt("price","28").putOpt("type","good"));
menu.add(new JSONObject().putOpt("name","鱼香肉丝").putOpt("price","30").putOpt("type","good"));
menu.add(new JSONObject().putOpt("name","肉夹馍").putOpt("price","6").putOpt("type","normal"));
menu.add(new JSONObject().putOpt("name","煎饼").putOpt("price","6").putOpt("type","normal"));

Map<String, List<JSONObject>> type = menu.stream()
    .collect(Collectors.groupingBy(jsonObject -> jsonObject.getStr("type")));
System.out.println(type);
//输出
//{normal=[{"price":"6","name":"肉夹馍","type":"normal"}, {"price":"6","name":"煎饼","type":"normal"}], good=[{"price":"28","name":"宫保鸡丁","type":"good"}, {"price":"30","name":"鱼香肉丝","type":"good"}]}
复制代码

And also a method similar to the packet partitioningBy (), a partition, but it is located in the parameter booleantype.

My public number

My public blog for synchronization No.

Guess you like

Origin juejin.im/post/5dcffde5f265da0bc40cedae