I'd like to pass through an array and make two new arrays: one with the elements that meet a certain condition, and one that does not.
Is this possible in one pass, or will I necessarily have to pass twice: once to determine how big the new arrays should be, and again to fill these arrays? I can see how this would work with another programming language or with a different data structure, but with java this does not seems possible.
Chris Gerken
16.4k6 gold badges48 silver badges61 bronze badges
1 Answer 1
You want to use Arrays? Or it may be collection? If so then:
String[] st = new String[] {"asas", "dsdsdsd", "sfdsfdsf", "dsfsdfdsfdsfs"};
List<String> s1 = new ArrayList<String>();
List<String> s2 = new ArrayList<String>();
for (String s: st) {
if (s.length>5)
s1.add(s)
else
s2.add(s);
}
Adam Mihalcin
14.5k4 gold badges38 silver badges52 bronze badges
answered Mar 9, 2012 at 22:38
lang-java
ArrayList<T>
?theList.partition(x => x.length > 5)
or similar. (There is a correlation between the ease-of-use-of-collections and my desire to use a particular language.)