将ArrayList拆分为另一个ArrayLists

时间:2013-10-16 01:44:41

标签: java

如何将ArrayList拆分为多个ArrayLists。

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

就像[Ram M sham m rani Fm]

我想将其拆分为[ Ram m] [sham m ] [Rani Fm]

4 个答案:

答案 0 :(得分:1)

我假设在你的Person类中,你有一个保存person类别值的变量和另一个保存名称值的变量。这样的事情呢?

import java.util.ArrayList;

public class Test {

ArrayList<Person> pers = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
ArrayList<String> categories = new ArrayList<>();
Test() {
    pers.add(new Person("Ram", "m"));
    pers.add(new Person("sham", "m"));
    pers.add(new Person("rani", "fm"));
    for (Person per : pers) {
        names.add(per.name);
        categories.add(per.category);
    }
    for (String name: names) {
        System.out.println("Name: " + name);            
    }
    for (String category: categories) {
        System.out.println("Category: " + category);
    }
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    new Test();
}

class Person {

    String name;
    String category;

    Person() {
        this("A", "A");
    }

    Person(String name, String category) {
        this.name = name;
        this.category = category;
    }
}
}

输出:

Name: Ram
Name: sham
Name: rani
Category: m
Category: m
Category: fm

答案 1 :(得分:1)

看看ArrayUtils in the Commons。有一些方法可以帮助您找到一个很好的清洁解决方案:

又名SubArray()

答案 2 :(得分: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);                    
           }
       }
 }

<强>输出

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

答案 3 :(得分:0)

假设列表首先包含名称,然后是性别,您可以执行以下操作。

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