【问题标题】:How to iterate over a list to get specific attributes only如何遍历列表以仅获取特定属性
【发布时间】:2015-10-01 02:21:31
【问题描述】:

我有一个清单

List<Widget> specialWidgets = WidgetUtil.getInstance().findAllWidgetsForType(WidgetType.UNIQUE);

返回一个包含小部件 ID 和名称的列表

[Widget [id=4f90b95d-8eb3-41e0-b3b1-d9ea516e1012, name=blue widget]

如何使用 java 7 将 id 放入列表中?

【问题讨论】:

  • 请更新问题或标签以包含您正在使用的库。 (即 Widget、WidgetUtil 和 WidgetType 是从哪里来的?)
  • @Jason:我知道你是这方面的新手,但你需要更清楚你的问题。这很可能很快就会被标记为重复。

标签: java arrays collections iterator listiterator


【解决方案1】:

您需要遍历刚刚从服务接收到的列表,从每个 Widget 对象中提取 ID 字段并将该信息推送到另一个 List 对象中。

List<Guid> specialWidgetsIds = new List<Guid>();

foreach (Widget w in specialWidgets) {
    specialWidgetsIds.Add(w.id);
}

【讨论】:

    【解决方案2】:

    我认为您应该创建新列表,然后将 specialWidgets 中的 id 添加到新列表中

    【讨论】:

      【解决方案3】:
      • 如果你使用的是jkd8,使用lambda表达式进行转换

      List specialWidgetIds = WidgetUtil.getInstance().findAllWidgetsForType(WidgetType.UNIQUE).stream().map(p -> p.getId()).collect(Collectors.toList());

      • 如果您使用的是 jdk7、jdk6... 就按照 pkamathk 的建议去做吧。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多