Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Knute Johnson Newsgroups: comp.lang.java.programmer Subject: Re: Removing an element while iterating over a List with enhanced for? Date: Thu, 16 Feb 2017 11:17:36 -0600 Organization: A noiseless patient Spider Lines: 41 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit Injection-Date: Thu, 16 Feb 2017 17:15:47 -0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="0bf6f47c7f70fa55385c26ec4c1cc8a3"; logging-data="22393"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/W3fiQ5/4mMdVzdXv9Ch6j" User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Thunderbird/45.7.1 In-Reply-To: Cancel-Lock: sha1:Q4Axw0wpnQNWbx/i3c/NTjx8w6U= Xref: csiph.com comp.lang.java.programmer:36290 On 2/15/2017 21:43, Arne Vajhøj wrote: > On 2/15/2017 5:56 PM, Knute Johnson wrote: >> An enhanced for loop on a List is no different than using an Iterator >> right? So is there any problem removing the current element from the >> list while using the enhanced for loop? I couldn't find anything that >> said it was OK or not OK in the JLS. > >> List list = Stream.of(1,5,7,9,13).collect(toList()); >> >> for (Integer i : list) >> if (i == 9) >> list.remove(i); >> >> list.forEach(System.out::println); >> >> list = Stream.of(1,5,7,9,13).collect(toList()); >> >> Iterator iter = list.iterator(); >> >> while (iter.hasNext()) >> if (iter.next() == 9) >> iter.remove(); >> >> list.forEach(System.out::println); > > Since you are already using streams and lambdas then why not: > > list = list.stream().filter(v -> v != 9).collect(toList()); > > ? > > Arne > > That's where I'm going eventually. The real code is a lot more complex and I got distracted by something that shouldn't have worked :-). -- Knute Johnson