Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: How to parse an array? Date: Tue, 20 Jun 2017 16:23:46 -0400 Organization: A noiseless patient Spider Lines: 52 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Tue, 20 Jun 2017 20:20:07 -0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="1b8cadd5b8731a26f2c7d28fbe01c1bc"; logging-data="28274"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX197xJa7V6/PdN4E7kT277iA" User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Thunderbird/52.2.0 In-Reply-To: Content-Language: en-US Cancel-Lock: sha1:wRJfQ/542rA2zeCOGCdWJq1JgG8= Xref: csiph.com comp.lang.java.programmer:36686 On 6/20/2017 3:18 PM, Eric Douglas wrote: > I'm writing a method to take 2 arrays and return the subset of the first array. Is there a more efficient way than creating a new array and iterating? It would remove some few obstacles to understanding if you were to stop treating `ArrayList' and `array' as synonyms. In return, I will forswear using `4' to mean `for'. Deal? > ArrayList list1 = new ArrayList(); > list1.add("AA"); > list1.add("CC"); > list1.add("DD"); > list1.add("BB"); > list1.add("EE"); > ArrayList list2 = new ArrayList(); > list2.add(1); > list2.add(3); > ArrayList retval = new ArrayList(); `new ArrayList<>(list2.size())' might be a bit more efficient, as it uses the minimum memory and avoids any expansions of too-short intermediate lists. > for (int i : list2) { > retval.add(list1.get(i)); Aside: This might throw IndexOutOfBoundsException. If you "know things" about the length of `list1' and the contents of `list2', that might not be a concern. > } > Collections.sort(retval); Aside: You could get a NullPointerException during the sort if `list1' contains any nulls that are selected by the contents of `list2'. Again, this may not be a concern if you have sufficient prior knowledge. > System.out.println(retval); There are certainly other ways to write this -- as a stream pipeline, for example. Whether the alternatives would be more or less efficient is something you'd need to measure for yourself. My guess (*no* hard evidence, mind you) is that "manual" methods would win if `list2' is short, streams would win if it's Really Long (because you could parallelize), and there'd probably be a rather wide intermediate range of lengths where differences might be difficult to measure. And, of course, you could always use arrays instead. -- esosman@comcast-dot-net.invalid Thirteen hundred ten days to go.