Java8 use Stream gracefully handle the collection

Explanation

An array is a collection of data structures and we often used before jdk1.8, handling collections and arrays is not very convenient. But by the JDK1.8 after using Stream processing set will make the code more clear and concise. As a developer, in fact, is very necessary to learn the use of the new features, even said that the project does not use. Although JDK1.8 has been released a few years, but still found that many people do not use the new API JDK1.8 brought us. For example, in an article written before still use SimpleDateFormat? Java8 are released N years, it LocalDateTime turn , explained the new API on the JDK1.8 time, you can also take a look.


Stream class common api

Here are the more common api, you want to see more specific API, you can refer to jdk1.8 official documents, where a more detailed description.

initialization

Stream to initialize a conventional two approaches:

Method One: List of stream () method

 @Test
 public void listInit(){
 List<String> list = new ArrayList<>();
 list.add("apple");
 list.add("banana");
 Stream<String> stream = list.stream();
 }
复制代码

Method two: Stream.of () method

 @Test
 public void streamOfInit(){
 // 第一种
 Stream<String> stream = Stream.of("a", "b", "c", "d");
 
 // 第二种
 String [] strings = {"a","b","c"};
 Stream<String> stream1 = Stream.of(strings);
 }
复制代码

filter filter

Selection of the required elements, such as: the example below to filter out the string dog

/**
 * 过滤
 */
 @Test
 public void filter() {
 String[] strings = {"apple", "banana", "cat", "dog"};
 List<String> list = Stream.of(strings).filter(e -> !StringUtils.equals(e, "dog")).collect(Collectors.toList());
 System.out.println(JSON.toJSONString(list));
 }
复制代码

Output:

["apple","banana","cat"]
复制代码

map to generate a new set of

There are two classes

 @Data
 @AllArgsConstructor
 public static class Person {
 private Integer id;
 private String name;
 }
@Data
public static class Man {
 private Integer id;
 private String name;
}
复制代码

To be converted into a List List

 @Test
 public void map2() {
 List<Person> list = new ArrayList<>();
 list.add(new Person(1, "happyjava1"));
 list.add(new Person(2, "happyjava2"));
 List<Man> manList = list.stream().map(e -> {
 Man man = new Man();
 man.setId(e.getId());
 man.setName(e.getName());
 return man;
 }).collect(Collectors.toList());
 System.out.println(JSON.toJSONString(manList));
 }
复制代码

Output

[{"id":1,"name":"happyjava1"},{"id":2,"name":"happyjava2"}]
复制代码

Collectors.toMap spliced ​​into the list of required map

This is often used when the query list data to the database

 @Test
 public void testCollectToMap() {
 List<Person> list = new ArrayList<>();
 list.add(new Person(1, "happyjava1"));
 list.add(new Person(2, "happyjava2"));
 Map<Integer, Person> personMap = list.stream().collect(Collectors.toMap(Person::getId, e -> e));
 System.out.println(JSON.toJSONString(personMap));
 Map<Integer, String> nameMap = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));
 System.out.println(JSON.toJSONString(nameMap));
 }
复制代码

Output

{1:{"id":1,"name":"happyjava1"},2:{"id":2,"name":"happyjava2"}}
{1:"happyjava1",2:"happyjava2"}
复制代码

sort sort

sort method without parameters to support natural ordering of basic data types, type of packaging, String, etc. type

@Test
 public void sort() {
 // 自然顺序排序 基本数据类型 字符串
 List<String> collect = Stream.of("1", "5", "2", "9", "3", "4").sorted().collect(Collectors.toList());
 System.out.println(JSON.toJSONString(collect));
 List<Person> list = new ArrayList<>();
 list.add(new Person(1, "happyjava1"));
 list.add(new Person(2, "happyjava2"));
 // 自然顺序排序
 List<Person> personList = list.stream().sorted((o1, o2) -> {
 if(o1.getId() > o2.getId()){
 return 1;
 } else if(o1.getId().equals(o2.getId())){
 return 0;
 } else {
 return -1;
 }
 }).collect(Collectors.toList());
 System.out.println(JSON.toJSONString(personList));
 }
复制代码

Output

["1","2","3","4","5","9"]
[{"id":1,"name":"happyjava1"},{"id":2,"name":"happyjava2"}]
复制代码

skip and limit

This corresponds to the MySQL limit n, m, and MongoDB the skip, limit usage is consistent. It means that across a few rows, meaning to take a few lines of records.

 @Test
 public void skipAndLimit(){
 List<String> list = Stream.of("1", "5", "2", "9", "3", "4").skip(2).limit(3).collect(Collectors.toList());
 System.out.println(JSON.toJSONString(list));
 }
复制代码

Output

["2","9","3"]
复制代码

to sum up

Stream commonly used operations are listed here, Stream of course there are many other uses, also can not list them here, you need the reader to learn.

Reproduced in: https: //juejin.im/post/5d07a0406fb9a07f014ef6e6

Guess you like

Origin blog.csdn.net/weixin_34206899/article/details/93181301
Recommended