使用Java 8从列表中有选择地删除前N个 [英] Remove first N selectively from list using java 8
本文介绍了使用Java 8从列表中有选择地删除前N个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
查看问题注释.有选择地删除N个元素(条件是列表元素匹配删除")
See comments for question. Remove N elements selectively (Condition is that list element matches 'remove')
List<String> mylist = new ArrayList<>();
mylist.add("remove");
mylist.add("all");
mylist.add("remove");
mylist.add("remove");
mylist.add("good");
mylist.add("remove");
// Remove first X "remove".
// if X is 2, then result list should be "all, remove, good, remove"
// Use java 8 features only, possibly single line code.
// Please don't answer with looping, iterating, if conditions etc.
// Answer should use JDK 8 new features.
推荐答案
这是怎么回事:
List<String> filter(List<String> mylist, int x){
AtomicInteger index = new AtomicInteger(0);
mylist.removeIf(p -> p.equals("remove") && index.getAndIncrement() < x);
return myList;
}
当x = 0时,它会打印:
With x=0, it prints:
[全部删除,删除,删除,良好,删除]
[remove, all, remove, remove, good, remove]
使用x = 1时,它会打印:
With x=1, it prints:
[全部,删除,删除,良好,删除]
[all, remove, remove, good, remove]
x = 2时,它会打印:
With x=2, it prints:
[全部,删除,良好,删除]
[all, remove, good, remove]
在x = 3的情况下,它会打印:
With x=3, it prints:
[所有,很好,删除]
[all, good, remove]
这篇关于使用Java 8从列表中有选择地删除前N个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文