1

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,221
  • 6
  • 44
  • 59
SN.
  • 31
  • 1
  • 1
  • 2
  • 2
    Just determined not to use a more appropriate data structure like an `ArrayList`? – Kirk Woll Mar 09 '12 at 22:36
  • It definitely would be more appropriate, but I'm wondering if this is even possible with arrays. – SN. Mar 09 '12 at 22:37
  • 1
    @SN. It is possible. Just not for a strict definition of "one pass". The two approaches are 1) scan, create appropriate array sizes or 2) create full-sized arrays, process, and shrink (or pass around a "used length" or have another sentinel) to fit. Neither case is ideal, although it likely *Just Doesn't Matter* (but I second Kirk Woll ;-). This is also precisely why I avoid Java... –  Mar 09 '12 at 22:40
  • 1
    OT: @pst: you are avoiding java because you can't resize arrays? – stryba Mar 09 '12 at 22:45
  • @stryba I avoid Java because of everything it lacks that make dealing with simple collection operations painfully verbose and procedural ;-) Arrays in Java (and even the answer below) showcase this well, I think. For instance, I would much rather do: `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.) –  Mar 09 '12 at 23:04

1 Answers1

3

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,242
  • 4
  • 36
  • 52
MikhailSP
  • 3,233
  • 1
  • 19
  • 29