Java流会删除前三个元素

时间:2018-12-18 16:06:44

标签: java arraylist java-stream

我有按学生id排序的对象列表:

List<Student> arraylist = new ArrayList<>();
arraylist.add(new Student(1, "Chaitanya", 26));
arraylist.add(new Student(2, "Chaitanya", 26));
arraylist.add(new Student(3, "Rahul", 24));
arraylist.add(new Student(4, "Ajeet", 32));
arraylist.add(new Student(5, "Chaitanya", 26));
arraylist.add(new Student(6, "Chaitanya", 26));

我想使用 stream 并仅删除学生age等于26的前三个元素。 你能帮我这个忙吗?

2 个答案:

答案 0 :(得分:8)

您可以将make installfilter用作:

skip

这将导致列出年龄等于26岁的List<Student> finalList = arraylist.stream() .filter(a -> a.getAge() == 26) // filters the students with age 26 .skip(3) // skips the first 3 .collect(Collectors.toList()); 个学生,同时跳过前三个出现的此类学生。


另一方面,如果您只想从完整列表中排除这三个学生,也可以按照以下步骤操作:

Student

请注意,这可能会导致更改列表的原始顺序。

答案 1 :(得分:4)

首先通过流API搜索要删除的元素:

List<Student> toRemove = arraylist.stream()
                                  .filter(x -> x.getAge() == 26)
                                  .limit(3)
                                  .collect(toList());

然后从源列表中删除:

toRemove.forEach(arraylist::remove);

如果您不想突变来源,请先对其进行克隆:

List<Student> resultSet = new ArrayList<>(arraylist);
List<Student> toRemove = arraylist.stream().filter(x -> x.getAge() == 26).limit(3)
                                  .collect(toList());
toRemove.forEach(resultSet::remove);

毕竟,这可以使用迭代器更好地实现:

int counter = 0;
for (Iterator<Student> it = arraylist.iterator(); it.hasNext();){        
      if(counter == 3) break;
      Student student = it.next();
      if (student.getAge() == 26){
          it.remove();
          counter++;
      }
}
相关问题