从数组列表中读取数据,拆分并存储在另一个

时间:2015-10-21 16:42:06

标签: java arrays arraylist

我在从文本文件中逐行读取数据时遇到问题,将其存储在arraylist中。我必须从arraylist[0]读取数据,我必须对该数据执行split操作,我必须将数据存储在不同的数组中。

public class StatsOnData {
public static void main(String args[]) throws IOException {

    String gender;


     BufferedReader in = new BufferedReader(new FileReader("file path"));
        String str;

        List<String> list = new ArrayList<String>();`enter code here`
        while((str = in.readLine()) != null){
            list.add(str);
        }

        String[] stringArr = list.toArray(new String[0]);
        System.out.println(list.size());


        //spliting the array into a sub array
        StringBuilder temp = new StringBuilder();
        for(int i=1; i <= list.size(); i++){
           for( int j = 0; j < list[i]; j++){

              String line = null;

            while ((line = .readLine()) != null) {
                String[] values = line.split("|");
                for (String str1 : values) {
                    System.out.println(str);
                }

           }

        }

2 个答案:

答案 0 :(得分:0)

以分割形式打印每一行的内容,

for(int i=1; i <= list.size(); i++)
{
      String line = list.get (i) ;
      String[] values = line.split("|");
      for (String str1 : values) 
      {
                System.out.print(str);
      }
}

您甚至可以使用地图

Map<String,List<String>> genderNameList = new HashMap<String,List<String>>();
for(int i=1; i <= list.size(); i++)
{
      String line = list.get (i) ;
      String[] values = line.split("|");
      //assuming it won't be null 
      genderNameList.get ( values[1]).add(values[0]);// need tot take care about null 
}

如果你的字符串像peter || Mr | F || 23

List<Person> listOfObj = new ArrayList<Person> ();
for(int i=1; i <= list.size(); i++)
{
      String line = list.get (i) ;
      String[] values = line.split("|");
      //assuming it won't be null 
      Person p = new Person ( values) ;

}

人可以如下:

Class Person {
  private String name;
  private String gender;
  private int age; 

  //provide gettter and setter for all such fields. 
  Person ( String [] values)
  {
     name = values[0];
     gender = values[1];
     age = Integer.valuesOf ( values[2]) ;

    .... 
  }
}

答案 1 :(得分:0)

我不明白你的问题,但可能你想做这样的事情 -

BufferedReader in = new BufferedReader(new FileReader("file path"));
String str;
int countMale=0;
int countFemale=0;
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
    list.add(str);
}

for(String s:list){
    String[] splitValues=s.split("|");
    for(int i=0;i<splitValues.length;i++){
        if(splitValues[i].equalsIgnoreCase("m")){
            countMale++;
        }
        else if(splitValues[i].equalsIgnoreCase("f")){
            countFemale++;
        }
    }
}
System.out.println("Number of males: "+countMale);
System.out.println("Number of females: "+countFemale);

希望这有帮助!