我有一个未排序的列表,其中包含未知数量的项目,在 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 block ,但这是一个丑陋的解决方案。
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)));
关于java - 将列表内容排序为新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52783954/