return userList.stream().filter(user -> {String tagsStr = user.getTags();
使用 Stream API 來過濾 userList
中的用戶
解析 tagsStr
并根據標簽進行過濾
假設 tagsStr
是一個 JSON 格式的字符串,存儲了一個標簽集合。你希望過濾出包含所有指定標簽的用戶。
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;public List<SafetyUser> filterUsersByTags(List<String> tagNameList) {// 查詢所有用戶QueryWrapper<User> queryWrapper = new QueryWrapper<>();List<User> userList = userMapper.selectList(queryWrapper);// 使用 Gson 解析 JSON 字符串Gson gson = new Gson();Type setType = new TypeToken<Set<String>>() {}.getType();// 過濾用戶return userList.stream().filter(user -> {String tagsStr = user.getTags();if (StringUtils.isBlank(tagsStr)) {return false;}Set<String> tempTagNameSet = gson.fromJson(tagsStr, setType);tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());return tagNameList.stream().allMatch(tempTagNameSet::contains);}).map(this::getSafetyUser).collect(Collectors.toList());
}
Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {}.getType());
使用了 Gson
來將一個 JSON 格式的字符串解析為一個 Set<String>
類型
假設 tagsStr
是一個 JSON 格式的字符串,存儲了一個標簽集合。你希望將這個字符串解析為一個 Set<String>
。
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.Set;public class Example {public static void main(String[] args) {// 示例 JSON 字符串String tagsStr = "[\"tag1\", \"tag2\", \"tag3\"]";// 創建 Gson 實例Gson gson = new Gson();// 使用 TypeToken 獲取 Set<String> 的類型Type setType = new TypeToken<Set<String>>() {}.getType();// 解析 JSON 字符串為 Set<String>Set<String> tempTagNameSet = gson.fromJson(tagsStr, setType);// 輸出結果System.out.println(tempTagNameSet);}
}
Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {}.getType());
你的代碼片段中使用了 `Gson` 來將一個 JSON 格式的字符串解析為一個 `Set<String>` 類型。
### 完整代碼示例
假設 `tagsStr` 是一個 JSON 格式的字符串,存儲了一個標簽集合。你希望將這個字符串解析為一個 `Set<String>`。
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.Set;public class Example {public static void main(String[] args) {// 示例 JSON 字符串String tagsStr = "[\"tag1\", \"tag2\", \"tag3\"]";// 創建 Gson 實例Gson gson = new Gson();// 使用 TypeToken 獲取 Set<String> 的類型Type setType = new TypeToken<Set<String>>() {}.getType();// 解析 JSON 字符串為 Set<String>Set<String> tempTagNameSet = gson.fromJson(tagsStr, setType);// 輸出結果System.out.println(tempTagNameSet);}
}
### 代碼解釋
1. **創建 Gson 實例**:
?? Gson gson = new Gson();
?? 這里創建了一個 `Gson` 實例,用于后續的 JSON 解析。
2. **獲取 `Set<String>` 的類型**:
?? Type setType = new TypeToken<Set<String>>() {}.getType();
?? - `TypeToken` 是一個輔助類,用于獲取泛型類型的 `Type`。
?? - `new TypeToken<Set<String>>() {}.getType()` 會返回一個 `Type` 對象,表示 `Set<String>` 類型。
?? - 這是因為 Java 的泛型在運行時會被擦除,所以需要通過 `TypeToken` 來保留泛型信息。
3. **解析 JSON 字符串**:
?? Set<String> tempTagNameSet = gson.fromJson(tagsStr, setType);
?? - `gson.fromJson(tagsStr, setType)` 方法將 JSON 字符串 `tagsStr` 解析為 `Set<String>` 類型。
?? - `tagsStr` 應該是一個 JSON 數組格式的字符串,例如 `["tag1", "tag2", "tag3"]`。
4. **處理空值或異常**:
?? 在實際應用中,你可能需要處理 `tagsStr` 為空或格式不正確的情況。可以添加一些額外的檢查和異常處理:
try {if (StringUtils.isBlank(tagsStr)) {tempTagNameSet = new HashSet<>();} else {tempTagNameSet = gson.fromJson(tagsStr, setType);}} catch (Exception e) {// 處理解析異常tempTagNameSet = new HashSet<>();System.err.println("Error parsing tags: " + e.getMessage());}
tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
這行代碼使用了 `Optional` 類來處理可能為 `null` 的 `tempTagNameSet`。`Optional` 是 Java 8 引入的一個類,用于避免顯式的 `null` 檢查,使代碼更加簡潔和安全。
### 代碼解釋
- **`Optional.ofNullable(tempTagNameSet)`**:
? - 創建一個 `Optional` 對象,如果 `tempTagNameSet` 為 `null`,則返回一個空的 `Optional`;否則,返回一個包含 `tempTagNameSet` 的 `Optional`。
- **`.orElse(new HashSet<>())`**:
? - 如果 `Optional` 是空的(即 `tempTagNameSet` 為 `null`),則返回一個新的空 `HashSet`;否則,返回 `tempTagNameSet`。
### 作用
這行代碼的作用是確保 `tempTagNameSet` 不會為 `null`。如果 `tempTagNameSet` 為 `null`,則用一個空的 `HashSet` 替代,避免后續代碼中出現 `NullPointerException`。
### 示例
假設你從 JSON 字符串解析出的 `Set<String>` 可能為 `null`,你希望確保它不會為 `null`:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.*;public class Example {public static void main(String[] args) {// 示例 JSON 字符串String tagsStr = "[\"tag1\", \"tag2\", \"tag3\"]";// 創建 Gson 實例Gson gson = new Gson();// 使用 TypeToken 獲取 Set<String> 的類型Type setType = new TypeToken<Set<String>>() {}.getType();// 解析 JSON 字符串為 Set<String>Set<String> tempTagNameSet = null; // 假設解析失敗,tempTagNameSet 為 nulltry {tempTagNameSet = gson.fromJson(tagsStr, setType);} catch (Exception e) {e.printStackTrace();}// 確保 tempTagNameSet 不為 nulltempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());// 輸出結果System.out.println(tempTagNameSet);}
}
### 優化和注意事項
1. **異常處理**:
?? 在實際應用中,應該處理可能的異常,例如 JSON 格式錯誤或解析失敗。
?? try {
?????? tempTagNameSet = gson.fromJson(tagsStr, setType);
?? } catch (Exception e) {
?????? log.error("Error parsing tags: {}", tagsStr, e);
?????? tempTagNameSet = new HashSet<>();
?? }
?
2. **空值處理**:
?? 如果 `tagsStr` 為空或 `null`,應該提供一個默認值。
?? if (StringUtils.isBlank(tagsStr)) {
?????? tempTagNameSet = new HashSet<>();
?? } else {
?????? try {
?????????? tempTagNameSet = gson.fromJson(tagsStr, setType);
?????? } catch (Exception e) {
?????????? log.error("Error parsing tags: {}", tagsStr, e);
?????????? tempTagNameSet = new HashSet<>();
?????? }
?? }
?
3. **性能優化**:
?? 如果你需要頻繁解析類似的 JSON 字符串,可以考慮緩存 `Gson` 實例,避免每次創建新的實例。
### 完整的過濾方法
結合你的需求,以下是一個完整的過濾方法示例:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;public List<SafetyUser> filterUsersByTags(List<String> tagNameList) {// 查詢所有用戶QueryWrapper<User> queryWrapper = new QueryWrapper<>();List<User> userList = userMapper.selectList(queryWrapper);// 使用 Gson 解析 JSON 字符串Gson gson = new Gson();Type setType = new TypeToken<Set<String>>() {}.getType();// 過濾用戶return userList.stream().filter(user -> {String tagsStr = user.getTags();Set<String> tempTagNameSet = new HashSet<>();try {if (StringUtils.isNotBlank(tagsStr)) {tempTagNameSet = gson.fromJson(tagsStr, setType);}} catch (Exception e) {log.error("Error parsing tags for user {}: {}", user.getId(), tagsStr, e);}tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());return tagNameList.stream().allMatch(tempTagNameSet::contains);}).map(this::getSafetyUser).collect(Collectors.toList());
}
?
。
?