【问题标题】:What best way to populate java list with separate elements and elements from other lists?用其他列表中的单独元素和元素填充 java 列表的最佳方法是什么?
【发布时间】:2013-08-07 17:41:17
【问题描述】:

我需要创建一个链表并用容器中的“容器”和“元素”填充它。

这是我的代码:

public List<WebElement> getExpectedElements(){
    List<WebElement> list = new LinkedList<WebElement>(Arrays.asList(
            inetConnection,
            wiredConnection,
            phonesConnection,
            usbConnection,
            wifiConnection
    ));
    list.addAll(inetConnection.getExpectedElements());
    list.addAll(wiredConnection.getExpectedElements());
    list.addAll(phonesConnection.getExpectedElements());
    list.addAll(usbConnection.getExpectedElements());
    list.addAll(wifiConnection.getExpectedElements());
    return list;
}

在 java 中有什么方法可以让它变得更好(更简洁、DRY 等)?

【问题讨论】:

  • 你能把列表传递给填充它的对象吗?
  • “更好”是什么意思?
  • @SotiriosDelimanolis 这与该对象的职责不符...至少在我的对象模型中...
  • @yashaka 您只需要更改 List 返回的 List 的初始化方式,例如,inetConnection.getExpectedElements()
  • @RobertHarvey 我的意思是更短,更简洁,更干......下面的python代码至少会更短:) ........ list = [[con] + con.getExpectedElements for con in [inetCon, wiredCon, phonesCon, usbCon, wifiCon]]; return reduce(lambda x,y: x+y, list) #or: return sum(list, []) ...... ...也许这并不完美,但比主题中的java代码更好:)

标签: java list collections linked-list


【解决方案1】:

你至少可以引入一个循环:

List<WebElement> containers = Arrays.asList(inetConnection,
        wiredConnection,
        phonesConnection,
        usbConnection,
        wifiConnection);
List<WebElement> list = new LinkedList<WebElement>(containers);
for (WebElement e : containers)
    list.addAll(e.getExpectedElements());

【讨论】:

  • 如果我的 WebElements 有 .getExpectedElements() 方法,那将是更好的选择...但只有“容器”实现 HaveExpectedElements 接口并具有此方法...制作 LIst 的结果列表会对我来说还不够,因为我需要对列表元素进行一些 WebElement 的操作。
猜你喜欢
  • 2010-10-14
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
相关资源
最近更新 更多