【问题标题】:Iterate over heterogeneous list迭代异构列表
【发布时间】:2016-02-18 19:30:04
【问题描述】:

我有一个返回列表的方法,如

public List<Object> getSomeData(SomeBean sb) {
    List<Object> data = Lists.newArrayList();
    data.add(sb.getId());  // Id->long
    data.add(sb.getName()); // name->String
    .....
    return data;
}

现在我必须遍历这个列表,每次都必须检查类型

        for (int i = 0; i < data.size(); i++) {
            if (data.get(i) instanceof String) {
                 //append
            } 
            if (data.get(i) instanceof Long) {
               //append
            } 
         ....
        }

我需要在循环中追加列表的元素。 他们是否有更好的方法来实现这一点,可能不使用 instanceof 运算符。

【问题讨论】:

  • 为什么要将名称和 ID 添加到同一个列表中?如果它们有关系,您可以使用一个类来定义该关系。如果他们没有 - 他们不应该在同一个名单上。
  • 拥有这样的列表首先是问题所在。如果你必须混合不同类型的对象,那你就做错了。

标签: java loops data-structures collections


【解决方案1】:

您应该为该数据创建一个类并返回它的一个实例,而不是 List

class SomeEntity {
  long id;
  String name;

  public SomeEntity(long id, String name) {
    this.id = id;
    this.name = name;
  }

  public long getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  @Overrides
  public String toString() {
    return id + " " + name;
  }
}

只需在您的代码中使用它:

public SomeEntity getSomeData(SomeBean sb) {
    SomeEntity entity = new SomeEntity(sb.getId(), sb.getName());
    return entity;
}

编辑:您可以覆盖该类的toString() 方法并在您的代码中使用它(在上面添加)

【讨论】:

  • 其实我必须在循环中追加 list 的元素。
  • @Abs 重写 toString() 方法
【解决方案2】:

给你:

    final List<Object> someData = new ArrayList<>();
    someData.add("stringValue"); //String 
    someData.add(1L); //Long Value

    final String result = someData.stream()
    .map(String::valueOf)
    .collect(Collectors.joining(" "));

    System.out.println(result);

【讨论】:

    猜你喜欢
    • 2013-04-09
    • 2017-07-26
    • 2020-11-06
    • 2014-03-21
    • 2017-04-03
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多