Java8使用Stream優雅地處理集合


說明

集合和數組是我們經常會用到的數據結構,在jdk1.8之前,集合和數組的處理並不是很便捷。但是到了JDK1.8之后,使用Stream處理集合會使代碼變得更加的簡潔明了。作為一名開發者,其實很有必要學習新特性的用法,即使是說項目中沒有采用。雖然JDK1.8已經發布數年,但是還是發現很多人都不會使用JDK1.8給我們帶來的新的API。比如之前寫過的一篇文章還在用SimpleDateFormat?Java8都發布N年了,轉LocalDateTime吧,講解了JDK1.8時間上的新API,大家也可以看看。


Stream類的常用api

這里列舉了比較常用的api,想要查看更加具體API,大家可以參考下jdk1.8官方文檔,那里有更加詳細的描述。

初始化

初始化一個Stream常用到兩種方法:

方法一:List的stream()方法

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

方法二:Stream.of()方法

 @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過濾

挑選需要的元素,比如:下方例子把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));
 }

輸出結果:

["apple","banana","cat"]

map 生成新的集合

這里有兩個類

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

把一個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));
 }

輸出結果

[{"id":1,"name":"happyjava1"},{"id":2,"name":"happyjava2"}]

Collectors.toMap 把list拼接成需要的map

這個在向數據庫查詢list數據的時候經常用到

 @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));
 }

輸出結果

{1:{"id":1,"name":"happyjava1"},2:{"id":2,"name":"happyjava2"}}
{1:"happyjava1",2:"happyjava2"}

sort排序

無參的sort方法支持基本數據類型,包裝類型,String等類型的自然順序排序

@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));
 }

輸出結果

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

skip和limit

這個相當於MySQL的limit n,m,與MongoDB的skip、limit用法是一致的。意思就是跨過幾行記錄,取幾行記錄的意思。

 @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));
 }

輸出結果

["2","9","3"]

總結

常用的Stream操作都在這里列舉了,當然Stream還有很多其他的用法,這里也沒法一一列舉,需要讀者自己去學習。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM