定義對象實體
package com.elon.model;
/**
* 簡單用戶實體類
*
* @author elon
*/
public class User {
/**
* 用戶賬號
*/
private String account = "";
/**
* 用戶名
*/
private String name = "";
/**
* 年齡
*/
private int age = 0;
public User() {
}
public User(String account, String name, int age){
this.account = account;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
場景一 根據屬性過濾對象
/**
* 使用流過濾數據.
*
* @author elon
*/
public static void filterUser(List<User> userList) {
// 1、過濾數據
List<User> filterUserList = userList.stream().filter(u->u.getAge() > 12).collect(Collectors.toList());
// 2、打印過濾結果數量
System.out.printf("過濾後的數據:%s%n", new Gson().toJson(filterUserList));
}
場景二 提取對象中的屬性
/**
* 提取對象中的某個屬性值。
*
* @param userList 用戶對象列表
* @author elon
*/
public static void distillField(List<User> userList) {
List<String> nameList = userList.stream().map(User::getName).collect(Collectors.toList());
// 打印提取的用戶名
System.out.printf("打印提取的用戶名:%s%n", new Gson().toJson(nameList));
}
場景三 按對象屬性分組
基於對象中的某個屬性分組,屬性值相同的對象放一組。
/**
* 根據某個屬性對對象做分組.
*
* @param userList 用戶列表
* @auhtor elon
*/
public static void groupUser(List<User> userList) {
Map<Integer, List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getAge));
System.out.printf("分組後的對象:%s\n", new Gson().toJson(userMap));
}
場景四、對象列表轉換爲Map
將list轉換爲Map的目的是爲了在後面可以快速查詢。
package com.elon.service;
import com.elon.model.User;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Transform2MapClass {
/**
* 提取列表中的對象屬性,轉換爲Map
*
* @param userList 用戶對象列表
* @author elon
*/
public static void transform2Map(List<User> userList) {
Map<String, Integer> account2AgeMap = userList.stream().collect(Collectors.toMap(
User::getAccount, User::getAge, (k1,k2)->k1, HashMap::new));
System.out.printf("提取的用戶賬號和年齡鍵值對:%s\n", new Gson().toJson(account2AgeMap));
Map<String, User> account2UserMap = userList.stream().collect(Collectors.toMap(User::getAccount, user -> user));
System.out.printf("提取的用戶賬號和對象鍵值對:%s\n", new Gson().toJson(account2UserMap));
}
}