-2

How can I split an ArrayList into multiple ArrayLists.

ArrayList < Person>  pers = new ArrayList<Person>();

is like [Ram M sham m rani Fm]

I want to split this into [ Ram m] [sham m ] [Rani Fm].

2
  • 1
    What are the criteria to split? And what have you attempted? Commented Oct 16, 2013 at 1:47
  • because to get namelist and category list separate. if i split like above then i will make later into arraylist of[ram,sham,rani] and [m m fm] Commented Oct 16, 2013 at 1:57

3 Answers 3

1

Take a look at ArrayUtils in the Commons. There are a few methods in there that would help you get to a nice clean solution:

aka SubArray()

Sign up to request clarification or add additional context in comments.

Comments

0

Assuming list contains names first and then gender, you can do following.

   for(int i=0; i< pers.size(); i+=2){
                List<Person> subList = peers.subList(i,i+2);
                System.out.println(subList);
    }

Comments

0
class Person{
    String name;
    String sex;
    public Person(String name, String sex) {
        super();
        this.name = name;
        this.sex = sex;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return  name +" "+  sex ;
    }
}

public class SplitArrayList {
      public static void main(String[] args) {
           ArrayList < Person>  pers = new ArrayList<Person>();
           pers.add(new Person("Ram", "M"));
           pers.add(new Person("sham", "M"));
           pers.add(new Person("rani", "FM"));
           for (int i=0;i<pers.size();i++) {
                List<Person> subList = pers.subList(i, i+1);
                System.out.println(subList);                    
           }
       }
 }

Output

[Ram M]
[sham M]
[rani FM]

3 Comments

getting output like [ Ram m
int i=0;i<pers.size();i= i+2 ....?
@KanagaveluSugumar why i+2.....he needs one element in the sublist

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.