您好,希望在Java中Map的迭代过程中为您提供一个跳过索引的帮助。 我有一个包含10个元素的地图,我想跳过索引8上的元素,我该如何实现目标。 我尝试使用streams()的skip()方法,但是它从开始到输入的计数都跳过了元素。以下是我的方法...
public void copyRow(Row row){
this.clear();
row.entrySet().stream().skip(8).forEach(e ->
this.put(e.getKey(),new Cell(e.getValue().getRowNo(),e.getValue().getColNo(),e.getValue().getValue()))
);
是否有其他方法可以在流中进行?
答案 0 :(得分:2)
哈希图没有排序,因此没有“索引”的概念。没有人知道索引8的条目是什么-每次可能都不同。
一个更好的主意是检查密钥。如果没有与要跳过的值关联的固定键,则可能应该设计数据的存储方式。因为如果是这样,那么您将基于不存在的“索引”概念来存储数据,这将无法很好地工作。
要跳过特定键,只需致电filter
:
row.entrySet().stream()
.filter(e -> !e.getKey().equals(someKeyThatIdentifiesTheEntryAtIndex8))
.forEach(e ->
this.put(e.getKey(),new Cell(e.getValue().getRowNo(),e.getValue().getColNo(),e.getValue().getValue()))
);
如果您使用的是具有“索引”概念的集合(例如数组或列表),则可以执行以下操作:
int[] a = {1,2,3,4,5,6,7,8,9,10,11};
IntStream firstPart = Arrays.stream(a).limit(7);
IntStream secondPart = Arrays.stream(a).skip(8);
IntStream finalStream = IntStream.concat(firstPart, secondPart);
finalStream.forEach(System.out::println);