Skip to content
Advertisement

How to split an array of objects in java or Kotlin?

I have already asked one question about this here but, that answers about only strings. I could not edit that as there a couple of answers there already.


Now, I get it how to split it with a space as given in that post. But, how can I split it with objects of custom class like this:

public class User{
   private boolean isAdult = false;
   private int age = 0;

   @Override
   public String toString(){
      return "User : { isAdult = " + isAdult + "        age = " + age + "}"
   }

   // getters and setters
}

Now, I want to split on places where isAdult is false. For example I have this array:

[User : { isAdult = true         age = 19}, User : { isAdult = false         age = 10}, User : { isAdult = true         age = 38}, User : { isAdult = false         age = 17}, User : { isAdult = true         age = 19}]

Now, on splitting of isAdult to being false, it will be like this:

Array1 = [User : { isAdult = true         age = 19}]
Array2 = [User : { isAdult = true         age = 38}]
Array3 = [User : { isAdult = true         age = 19}]

So, how can I achieve this in java or Kotlin

Advertisement

Answer

Based on tquadrat’s answer (in Java):

public static class User{
        boolean isFalse;
        int value;

        public User(boolean b, int v){
            this.isFalse = b;
            this.value = v;
        }

        public String toString() { return "User("+this.isFalse+", "+this.value+")"; }
}


 public static void main(String[] args) {
        User[] users = {new User(true, 5), new User(true, 1),new User(false, 7),
                new User(true, 10), new User(false, 3)};
        ArrayList<User[]> output = new ArrayList<>();

        int start = 0;
        int end = 0;
        while( end < users.length )
        {
            if( users[end].isFalse == false)
            {
                output.add( Arrays.copyOfRange( users, start, end  ));
                start = end + 1;
            }
            ++end;
        }
        if( start < end ) output.add( Arrays.copyOfRange( users, start, end ));

        for (User[] arr: output){
            System.out.println(Arrays.toString(arr));
        }

    }

Giving output:

[User(true, 5), User(true, 1)]
[User(true, 10)]
Advertisement