[英]Sort list content to new lists
我有一個未排序的列表,其中的項目數量未知,范圍為1000。這些項目都包含一個標簽,該標簽確定應該去的地方。 為避免多次遍歷列表中的每個項目,我想將此列表拆分為一定數量的子列表,這些子列表僅包含某些標簽的項目。
List<Item> allItems = getItemsFromSomewhere();
List<Item> itemsLabeledA1 = new ArrayList<>();
List<Item> itemsLabeledA2 = new ArrayList<>();
List<Item> itemsLabeledB1 = new ArrayList<>();
...
List<Item> itemsLabeledL3 = new ArrayList<>();
為了使問題更復雜,某些列表要求添加一系列項目,這就是為什么每個項目都被標記為“ A1”,“ A2”,“ A3”之類的原因。 這些列表要求將每個帶有A標簽的項目添加到它們中。 但是,並非所有標簽都具有這些聚合列表。 我可能必須匯總所有帶有A標簽的項目,而不是匯總所有帶有B標簽的項目,同時還要在自己的列表中對A1,B1等進行排序。
給定上面的示例,我如何在一次迭代中優雅地拆分整個列表? 我最初的想法是使用ifs或switch塊,但這是一個丑陋的解決方案。
allItems.forEach(item -> {
if (item.getLabel().contains("A1")) {
itemsLabeledA1.add(item);
allItemsLabeledA.add(item);
}
else if (item.getLabel().contains("B1")) itemsLabeledB1.add(item);
...
else if (item.getLabel().contains("L3")) itemsLabeledL3.add(item);
});
有沒有更好的辦法?
我將在兩個單獨的流操作中使用groupingBy :
Map<String, List<Item>> allByLabel = allItems.stream().collect(
Collectors.groupingBy(Item::getLabel));
Map<String, List<Item>> allByLabelStart = allItems.stream().collect(
Collectors.groupingBy(item -> item.getLabel().substring(0, 1)));
也許您可以嘗試使用HashMap
,其中鍵是標簽,值是子列表?
HashMap<String, List<Item>> map = new HashMap<String, List<Item>>();
for (String label : labels) {
map.put(label, new List<Item>);
}
allItems.forEach(item -> {
String label = item.getLabel();
map.get(label).add(item);
}
看來您正在分類商品。 為此,您需要根據規范創建不同的組,然后將每個項目添加到其組中。 如果我正確理解您的要求,則可以按以下步驟完成操作:
Map<String, List<Item>> map = new LinkedHashMap<>(); // keeps insertion order
allItems.forEach(it -> {
String lbl = it.getLabel();
map.computeIfAbsent(lbl, k -> new ArrayList<>()).add(it);
if (needsToBeAggregated(lbl)) {
map.computeIfAbsent(lbl.substring(0, 1), k -> new ArrayList<>()).add(it);
}
});
boolean needsToBeAggregated(String label)
是其中一種方法,您可以通過該方法確定是否應將項目添加到聚合組。
該解決方案不使用流,而是使用Java 8的Map.computeIfAbsent
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.