I'm trying to come up with a clean way to copy all elements of an ArrayList but one, based on its index.
In JavaScript we can filter by value, but also based on index as well. So what I'm trying to achieve will look something like that:
// nums is [] for(let i = 0; i <nums.length; i++) { let copyNums = nums.filter((n, index) => index !== i); } In Java best I could do so far is this, which is super long and verbose. Not to mention the I couldn't use i itself as it's not final otherwise I'm getting
Variable used in lambda expression should be final or effectively final
// nums is ArrayList for (int i = 0; i < nums.size(); i++) { final int index = i; List<Integer> allElementsWithoutCurr = IntStream.range(0, nums.size()) .filter(j -> j != index) .mapToObj(j -> nums.get(j)) .collect(Collectors.toList()); } Surely there is a better way to achieve this in Java?
List<Integer> copy = new ArrayList<>(orig); copy.remove(i);?j -> nums.get(j)withnums::get.AtomicIntegerinstance. You start by instantiating such an instance with default value 0 ( for examplenew AtomicInteger(0)). Then you callgetAndIncrement()on the instance from somewhere inside your stream. This will give you the current index and it also automatically increments the index by 1. So next time you call the method you'll get the updated index number.Stream#skipin this Answer.myList.stream().skip(1).filter( somePredicate ).toList()