我有10个项目的清单:
List<ServiceLineTypeResource> serviceLineList = serviceLineRepository.findAll();
打印输出:
[Backup, COI, Network, Oracle, SQL_Activities, Storage, Unix/Linux, Virtualization, Windows, #N/A]
...我想分成三个单独的列表,每个列表包含3个项目,不包括最终项目:
List<ServiceLineTypeResource> serviceLineListRow1 = serviceLineList.subList(0, min(serviceLineList.size(), 3));
List<ServiceLineTypeResource> serviceLineListRow2 = serviceLineList.subList(4, min(serviceLineList.size(), 7));
List<ServiceLineTypeResource> serviceLineListRow3 = serviceLineList.subList(8, min(serviceLineList.size(), 11));
我将每个添加到HashMap以及另一个不相关的列表:
HashMap<String, String> rowHashMap1 = new HashMap<>();
List<String> styleList = new ArrayList<>();
styleList.add("tile-pink");
styleList.add("tile-sqr tile-cyan");
styleList.add("tile-sqr tile-purple");
for (int i = 0; i < serviceLineListRow1.size(); i++) {
rowHashMap1.put(serviceLineListRow1.get(i).getName(), styleList.get(i));
System.out.println("Row 1: " + serviceLineListRow1.get(i).getName());
}
输出:
Row 1: Backup
Row 1: COI
Row 1: Network
Row 2: SQL_Activities
Row 2: Storage
Row 2: Unix/Linux
Row 3: Windows
Row 3: #N/A
出于某种原因,它总是跳过列表中的第8个项目Virtualization
并提供最后一个项目#
。我希望每个“行”列表都包含三个项目,我不希望#
出现在其中任何一个中。这是怎么回事?
答案 0 :(得分:2)
https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-
返回指定fromIndex(包含)和toIndex(独占)之间此列表部分的视图。
因此,如果您需要前9项,您需要这样做:
List<ServiceLineTypeResource> serviceLineListRow1 = serviceLineList.subList(0, min(serviceLineList.size(), 3));
List<ServiceLineTypeResource> serviceLineListRow2 = serviceLineList.subList(3, min(serviceLineList.size(), 6));
List<ServiceLineTypeResource> serviceLineListRow3 = serviceLineList.subList(6, min(serviceLineList.size(), 9));