【问题标题】:Java - Append to ArrayList Elements of a FileJava - 附加到文件的 ArrayList 元素
【发布时间】:2023-04-06 11:41:01
【问题描述】:

在 Java 中,我从 CSV 文件中读取数据,例如:

a,b,c,d
hello,hi,hey, 
bye,ciao,adios,
z,y,x,w

我想要的是创建一个字符串数组列表,例如:

["a hello bye z", "b hi ciao y", "c hey adios x", "d w"]

该文件非常非结构化,因此每一行的元素数量都不相同。我觉得 arrayList 将是最好的选择。到目前为止,我的伪代码是:

    ArrayList<String> list = new ArrayList<String>();    

        for(each line){

            for(int i = 0; i < numberOfElementsInEachLine; i++){

                list.add(i, list.get(i) + getLineElement(i));
            }
         }

实现这一目标的最佳方法是什么?谢谢。

【问题讨论】:

  • list.add(i, list.get(i) + getLineElement(i)); 你觉得这条线应该做什么?

标签: java loops arraylist


【解决方案1】:

方法 add on List 不会替换特定索引处的元素,而是添加一个新元素。 Javadoc for List interface

我建议使用 StringBuilder 实例和方法 append

【讨论】:

    【解决方案2】:

    也许你应该改变:

    list.add(i, list.get(i) + getLineElement(i));
    

    到:

    list.get(i) = "" + list.get(i) + getLineElement(i);
    

    因为 arraylist 的 add() 方法会在列表中添加一个新元素。

    【讨论】:

    • 我什至可以在两个循环的第一次迭代中使用 list.get(i) 吗?它不返回NULL吗?
    • 如果列表的第 i 个位置没有任何内容,那么您将获得 IndexOutOfBoundException 用于执行 list.get(i),请参阅此处的文档 docs.oracle.com/javase/7/docs/api/java/util/…
    【解决方案3】:

    基本上你希望文件的每一列都是一个数组列表。您需要执行以下操作:

    • 创建一个最初为空的数组列表列表
    • 以阅读模式打开文件
    • 逐行读取,直到不为空
    • 对于每一行,用逗号分隔(我假设逗号是分隔符)
    • 遍历以逗号分隔的块
    • 如果找到空值,则跳过它
    • 检查List&lt;String&gt;的列表是否在第i个位置包含List&lt;String&gt;,如果是,则检索该List&lt;String&gt;并将块[ith]添加到它并将其添加回主列表(在第i个位置替换旧的List&lt;String&gt;)
    • 如果main 列表在第i 个位置不包含List&lt;String&gt;,则创建一个新的List&lt;String&gt;,将块[i] 添加到其中,然后将其添加到主列表。

    将上述内容应用于您的输入

    循环通过a,b,c,d for List&lt;String&gt; 被添加到List&lt;List&lt;String&gt;&gt; 结构中,每个结构分别包含a,b,c and d

    循环通过第二行hello, hi and hey 前三个List 从List&lt;List&lt;String&gt;&gt; 结构中检索并再次更新和存储。

    假设您的第三行包含1,2,3,4,5(比上述两行多一个)。循环将从 List&lt;List&lt;String&gt;&gt; 中找到 4 List&lt;String&gt; 并分别用 1、2、3 和 4 更新它们,但是 5 呢? List&lt;List&lt;String&gt;&gt; 在 5 中不包含 List&lt;String&gt;,因为其他行只有 4 个块,所以创建一个新的 List&lt;String&gt; 并添加 5,然后将其添加到 List&lt;List&lt;String&gt;&gt;

    这是一个示例代码,它实际上执行了我上面描述的操作。我假设你想要 ArrayList 行中的东西。

    //list that stores list of strings
            List<List<String>> list = new ArrayList<List<String>>(); 
            try {
                //open file in read mode, change the file location 
                BufferedReader br = new BufferedReader(new FileReader("C:\\test_java\\content.txt")); 
                String line = ""; 
                //read each line as long as line != null which indicates end of file
                while((line=br.readLine()) != null) {
                    //split the line into chunks using comma as seperator
                    String[] chunks = line.split(","); 
                    //loop through chunks of vlaues
                    for(int i = 0; i < chunks.length; i++) {
                        //if chunks[i] is not empty
                        if(chunks[i].trim().length() > 0) {
                            //there is a List<String> in list.get(i) so get the List<String> update it and put it back
                            if(list.size() > i) {
                                List<String> temp = list.get(i); 
                                temp.add(chunks[i]); 
                                list.remove(i); 
                                list.add(i, temp);
                            } else {
                                //there was no list in list.get(i) so create a new List<String> and add it there
                                List<String> temp = new ArrayList<String>(); 
                                temp.add(chunks[i]); 
                                list.add(temp);
                            }
                        }
                    }
                }
                //close read stream
                br.close();
            } catch(Exception e){ 
                e.printStackTrace(System.out);
            }
    
            //print the list
            for(List<String> l: list) {
                System.out.println(l); 
            }
    

    您提供的输入文件的输出

    [[a, hello, bye, z], [b, hi, ciao, y], [c, hey, adios, x], [d, w]]
    

    如果您想获得问题中所示的精确输出,那么您可以遍历List&lt;List&lt;String&gt;&gt; 并从每个List&lt;String&gt; 的元素中创建一个单个字符串,并用双引号对其进行后缀。见下文,我使用 Java 8 的迭代器来迭代 List&lt;String&gt; 并创建 StringBuilder obj。

    String[] s = new String[list.size()];
    int i = 0; 
    for(List<String> l: list) {
        StringBuilder b = new StringBuilder("\""); 
        //java 8 loop through list and for each element add it to StrinbBuilder obj
        l.stream().forEach(e -> b.append(e + " "));
        b.append("\"");
        s[i++] = b.toString();
    }
    System.out.println(Arrays.toString(s));
    

    上面会给你

    ["a hello bye z ", "b hi ciao y ", "c hey adios x ", "d w "]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多