In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to use Stream, the new feature of java8". In daily operation, I believe many people have doubts about how to use Stream, the new feature of java8. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to use Stream, the new feature of java8". Next, please follow the editor to study!
First, define a food category:
Dish
Public class Dish {private final String name; private final boolean vegetarian; private final int calories; private final Type type; public boolean isVegetarian () {return vegetarian;} / / omit set,get,toString method}
Then create a static method and set it as a member variable of the class for testing.
Public static List getDishes () {return Arrays.asList (new Dish ("pork", false, 800, Dish.Type.MEAT), new Dish ("beef", false, 700, Dish.Type.MEAT), new Dish ("chicken", false, 400, Dish.Type.MEAT), new Dish ("french fries", true, 530, Dish.Type.OTHER), new Dish ("rice", true, 350, Dish.Type.OTHER) New Dish ("pizza", true, 550, Dish.Type.OTHER), new Dish ("prawns", false, 300, Dish.Type.FISH), new Dish ("salmon", false, 450, Dish.Type.FISH)) }
XNBqZ
Okay, now there's a need to find all the foods in the dish that are less than 400 calories and sort them by calorie size.
Before java8, and even after java8, some people would want to use an intermediate variable to keep the dishes that meet the requirements, and then sort them.
Public static List beforeJava8 () {List lowCaloricDishes = new ArrayList (); for (Dish dish: dishes) {if (dish.getCalories ())
< 400) { lowCaloricDishes.add(dish); } } lowCaloricDishes.sort(Comparator.comparingInt(Dish::getCalories));// lowCaloricDishes.sort((d1, d2) ->Integer.compare (d1.getCalories (), d2.getCalories ()); List res = new ArrayList (); for (Dish dish: lowCaloricDishes) {res.add (dish.getName ());} return res;}
Since I talked about method referencing in the previous article, I will use it directly here, but the following line also has the writing of ordinary Lambda expressions.
What's wrong with the above writing? you can find that lowCaloricDishes is only used once, and it's really a temporary variable. Can you skip the process of creating variables, you just give me the data, and I get what I want after filtering and sorting, just like the pipeline.
Public static List afterJava8 () {return dishes.stream () .filter (dish-> dish.getCalories ())
< 400) .sorted(Comparator.comparing(Dish::getCalories)) .map(Dish::getName) .collect(Collectors.toList());}流的定义 从支持数据处理操作的源生成的元素序列 流和集合有点类似,集合是数据结构,主要的目的是存储和访问元素,而流的主要目的是为了对元素进行一系列的操作。 通俗入门地来讲,集合就相当于你一部电影下载,流就相当于在线观看。其实只需要把流想成高级的集合即可。流有两个重要的特点: 流水线: 很多流本身会返回一个流,这样多个流就能链接起来和流水线一般。 内部迭代: 内部迭代也就是把迭代封装起来,如collect(Collectors.toList) ,与之相对应的外部迭代则是for-each 。 值得注意的是,和迭代器类似,流只能遍历一次 ,遍历完就可以说这个流消费掉了。 流的构建流的构建 流常用的构建方式有4种,其实要么是借助Stream 类的静态方法,要么是借助别人的类的静态方法。 由值创建流 由数组创建流 由文件生成流 由函数生成流 public static void buildStream() throws IOException { Stream byValue = Stream.of("java8", "c++", "go"); Stream empty = Stream.empty(); int[] nums = {1, 2, 3, 4, 5}; IntStream byInts = Arrays.stream(nums); Stream byFiles = Files.lines(Paths.get("")); Stream byFunction1 = Stream.iterate(0, n ->N * 2); Stream byFunction2 = Stream.generate (Math::random); Stream java = Stream.of ("java"); Operation of} stream
The stream operation that can be connected is called intermediate operation, and the operation that closes the stream is called terminal operation.
Generally speaking, an operation that returns a stream is called an intermediate operation, and an operation that is not a stream is called a terminal operation.
Image-20210414155605342
By looking up the java8 interface, we can know which interfaces are intermediate operations and which interfaces are terminal operations. As those interfaces are described too officially, it is estimated that no one will read them carefully if I post them, so if you want to see them, you can go directly to the official inspection.
Use of stream
Just according to the java API order on the official website, by the way, I didn't have a student flow before mainly because I felt that there would be a lot of interfaces. How could I remember so much? in fact, I found that there were really few of them these days, and basically I didn't have to remember them.
Img
First, build a list of numbers:
List numbers = Arrays.asList (1,2,3,4,5,5,5,5,6,7)
Intermediate operation
The middle operations are de-duplication, filtering, truncation, viewing, skipping, sorting, which I believe everyone can understand.
Public static void midOperation () {numbers.stream () .forEach (System.out::println); List filter = numbers.stream () .filter (n-> n% 2 = = 0) .forEach (Collectors.toList ()); numbers.stream () .limit (3) .forEach (System.out::println) Numbers.stream () .peek (integer-> System.out.println ("consume operation:" + integer)) .forEach (System.out::println); List skip = numbers.stream () .skip (2) .operations (Collectors.toList ()); numbers.stream () .sorted () .forEach (System.out::println);} Mapping of intermediate operations (map)
What needs to be mentioned separately is map and flatMap. Note that the map here is not the map of hashmap, but what is mapped or transformed.
Public static void midOperation () {List map = numbers.stream () .map (Object::toString) / / here int is mapped to string .map (Collectors.toList ());}
For flattened mapping, there is another requirement. Now there is a list of words such as {"hello", "world"} that returns different characters, that is, List.
It's not easy. Just map the words into letters and repeat them.
Public static void flatMapDemoNoral () {List words = Arrays.asList ("hello", "world"); List normal = words.stream () .map (str-> str.split (")) .destroy (Collectors.toList ());}
Img
Although it does work, notice that the function used in the mapping is split (), which returns String [], so the whole return is List
Then I will map each String [] array to a stream after mapping.
Public static void flatMapDemoMap () {List words = Arrays.asList ("hello", "world"); List usingMap = words.stream () .map (str-> str.split (")) .map (Arrays::stream) .requests (Collectors.toList ());}
Although you take off the hat of the array, you return List.
The purpose of flatMap is to solve this situation.
Public static void flatMapDemoFlatMap () {List words = Arrays.asList ("hello", "world"); List usingFlatMap = words.stream () .map (str-> str.split ("")) .flatMap (Arrays::stream) .floor () .floor (Collectors.toList ());}
To put it simply, map maps each element to a separate stream, while flattening map saves the element and maps it to a stream.
Find and match
In addition to collect () and forEach (), which are commonly used in writing examples above, terminal operations also have two major directions: search and specification.
Because there's nothing to say, just go to the code:
Public static void endOperationFindAndMatch () {if (dishes.stream (). NoneMatch (Dish::isVegetarian)) {System.out.println ("all dishes are non-vegetarian");} if (dishes.stream (). AllMatch (Dish::isVegetarian)) {System.out.println ("all dishes are vegetarian") } if (dishes.stream (). AnyMatch (Dish::isVegetarian)) {System.out.println ("at least one dish in the dish is vegetarian");} Optional any = dishes.stream () .filter (meal-> meal.getCalories () a * b); / / and the maximum Optional max = numbers.stream (). Reduce (Integer::max);} Optional class
It always appears that the return value is Optional, which is a container class, indicating that a value exists or does not exist, such as the initial findAny (), and may not be able to find a qualified dish. The main purpose of the introduction of Java8 is / in order not to return the problem-prone null.
Just talk about a few more commonly used api. As for the others, you can take a look at the official API on the Internet. We have talked about enough API today.
IsPresent () will return true if Optional contains a value, otherwise return false
The given code block is executed when there is a value for ifPresent (Consumer block)
Return a value if there is a value in get (), otherwise a NoSuchElement exception is thrown
OrElse () is returned if there is a value, otherwise a default value is returned.
Public static void optionalDemo () {/ / ifPresent dishes.stream () .filter (Dish::isVegetarian) .findAny () .ifPresent (dish-> System.out.println (dish.getName ()); / / isPresent boolean isLowCalories= dishes.stream () .filter (dish-> dish.getCalories ())
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.