需快速判斷某分行代碼 sgdBrId 是否包含在使用者可檢視分行清單 userViewBranchs 中。原始資料為逗號分隔字串,轉為 Set 後可達 O(1) 查找複雜度。
public boolean checkSGDLookPre(String sgdBrId, Ce_sysuser cuser) {
// 角色 6 為超級管理員,直接放行
if (cuser.getSu_RoleId() == 6) {
return true;
}
// 字串分割轉陣列
String[] strArray = cuser.getUserViewBranchs().split(",");
// 建立 HashSet,自動去重並提供 O(1) contains 查詢
Set<String> strSet = new HashSet<>();
CollectionUtils.addAll(strSet, strArray); // Apache Commons Collections 工具
return strSet.contains(sgdBrId);
}
| 技術點 | 說明 |
|---|---|
split(",") | 將逗號分隔字串轉為陣列 |
HashSet | 基於雜湊表,contains 平均 O(1) 時間複雜度 |
CollectionUtils.addAll | 一次將陣列所有元素加入集合,簡化迴圈寫法 |
| 角色判斷優先 | 提前返回避免不必要運算 |
// 無需額外依賴,純 JDK 實現
return cuser.getSu_RoleId() == 6 ||
Arrays.stream(cuser.getUserViewBranchs().split(","))
.collect(Collectors.toSet())
.contains(sgdBrId);
userViewBranchs 為空字串或 null,split 會產生長度為 1 的陣列(含空字串),建議加入防禦性檢查toUpperCase() 後再存入 SetHashSet 比 ArrayList 佔用更多記憶體,但查詢效能提升顯著將「需頻繁查詢是否包含」的集合資料結構從 List/陣列轉為 HashSet,是經典的以空間換時間優化手法。配合 CollectionUtils 或 Stream API,程式碼既簡潔又高效。