【问题标题】:How to create an ArrayList from a Intstream如何从 Intstream 创建 ArrayList
【发布时间】:2019-12-29 20:03:51
【问题描述】:

所以我想将 Person 放入一个数组列表中,但我需要使用流 我有 csv 文件,它给了我 infomartions 身份证;姓名;性别 以及使用那里的 id 将这些转换为 Person 对象的方法,

private Person readCSVLines(int id);

但我想创建一个方法给我一个数组列表,我知道有 807 id 并且不会再有一个了

我使用 toMap 尝试过这个,但它给了我一张地图,但我只想要一个 ArrayList:

public ArrayList<Person> getAllPerson() {
        try (IntStream stream = IntStream.range(1, personmax)) { // personmax is 807 here
            return stream.boxed().collect(
                    Collectors.toMap(
                            i -> i,
                            this::readCSVLines,
                            (i1, i2) -> {
                                throw new IllegalStateException();
                            },
                            ArrayList::new
                    )
            );
        }
    }

【问题讨论】:

    标签: java arraylist java-stream


    【解决方案1】:

    在您的情况下,您只需使用IntStream.range(from, to) 遍历所有行,并在.mapToObj() 的帮助下将每个行号转换为从 csv 读取的对象。在这种情况下使用boxed() 函数是多余的。 最后,你需要的是

        public List<Person> getAllPerson() {
           return IntStream
                .range(1, personmax) // personmax is 807 here
                .mapToObj(this::readCSVLines)
                .collect(Collectors.toList());
           }
        }
    

    另外,请注意,您的方法应该将接口作为返回类型 (List) 而不是具体实现 (ArrayList)

    【讨论】:

      【解决方案2】:

      不需要toMap 你需要mapToObjcollect 就像这样:

      public ArrayList<Person> getAllPerson() {
          return IntStream.range(1, personmax)
                  .mapToObj(this::readCSVLines)
                  .collect(Collectors.toCollection(ArrayList::new));
      }
      

      或者更好地使用List&lt;Person&gt; 而不是ArrayList&lt;Person&gt;

      public List<Person> getAllPerson() {
          return IntStream.range(1, personmax)
                  .mapToObj(this::readCSVLines)
                  .collect(Collectors.toList());
      }
      

      请注意,您不需要将IntStream.range 放入try catch 块中。我们没用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-17
        • 2021-11-01
        相关资源
        最近更新 更多