为了账号安全,请及时绑定邮箱和手机立即绑定

Java 8 逗号分隔字符串到对象属性

Java 8 逗号分隔字符串到对象属性

智慧大石 2022-05-21 16:44:31
我有三个逗号分隔的列表(公共汽车、汽车、自行车的列表),我正在尝试使用 Java 8 流将它们写入 Java 对象属性。请在下面找到我尝试过的内容:public class Traffic {    public int car;    public int bus;    public int cycle;    public Traffic(int car, int bus,int cycle){        this.car = car;        this.bus = bus;        this.cycle = cycle;    }}public class Test {    public static void main(String[] args) {        String bus = "5,9,15,86";        String car = "6,12,18,51";        String cycle = "81,200,576,894";        String[] busArray = bus.split(",");        String[] carArray = car.split(",");        String[] cycleArray = cycle.split(",");        List<Traffic> trafficList =                Arrays.stream(values)                        .mapToInt(Integer::parseInt)                        .mapToObj((int i,j) -> new Traffic(i,j))                        .collect(Collectors.toList());    }}我正在努力让所有流启动并注入对象属性。(在这种情况下,我想创建 4 个对象来填充所有 3 个属性。)基本上,我正在寻找如下内容:List<Traffic> trafficList =                Arrays.stream(carArray,busArray,cycleArray)                        .mapToInt(Integer::parseInt)                        .mapToObj((int i,j,k) -> new Traffic(i,j,k))                        .collect(Collectors.toList());
查看完整描述

3 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

如果要创建4个 Traffic 对象,则可以使用以下命令:

List<Traffic> collect = IntStream.range(0, busArray.length)
                          .mapToObj(i -> new Traffic(Integer.parseInt(busArray[i]),
                                                     Integer.parseInt(carArray[i]),
                                                     Integer.parseInt(cycleArray[i])))
                          .collect(Collectors.toList());


查看完整回答
反对 回复 2022-05-21
?
慕侠2389804

TA贡献1719条经验 获得超6个赞

您只需拆分字符串,然后将每个值映射到您的对象。

在这里,我假设值可以通过Traffic对象的构造函数传递。如果没有,您可以创建它并将其值设置在 2 个单独的行中。如果期望是整数,mapToInt则 是必需的。value

String original = "5,9,15,86";
String[] values = original.split(",");
List<Traffic> trafficList = 
   Arrays.stream(values)
      .mapToInt(Integer::parseInt)
      .map(Traffic::new) 
      .collect(Collectors.toList());


查看完整回答
反对 回复 2022-05-21
?
冉冉说

TA贡献1877条经验 获得超1个赞

在类 Traffic 中定义一个构造函数,该构造函数将整数作为参数并将其分配给类中的 value 属性。


    static class Traffic {

      private int value;

      public Traffic(int value) {

        this.value = value;

      }

    }

现在假设逗号分隔的字符串在字符串 commandList 中,如下所示。


String commaList = "1,3,5,6,7,8,9,100";

以下流指令将返回一个带有分配值的交通对象列表。


    List<Traffic> listOfIntegers = 

      Arrays.asList(commaList.split(","))

        .stream()

        .map(e -> new Traffic(Integer.valueOf(e)))

        .collect(Collectors.toList());


查看完整回答
反对 回复 2022-05-21
  • 3 回答
  • 0 关注
  • 575 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信