【问题标题】:Java Stream of Integer array to return List of Objects [closed]整数数组的Java流返回对象列表[关闭]
【发布时间】:2020-12-09 16:43:24
【问题描述】:

我有以下代码,我相信可以通过减少它的必要性来改进它。

有没有办法通过使用 Java Streams API 来为此重写?

它遍历一个整数列表,根据项目映射过滤,返回 id 上的匹配项。对我来说棘手的部分是它遍历 Integers,但返回 Items 的列表。

private  Map<Integer,Thing> thingMap = new HashMap<Integer,Thing>();
// populate thingMap
//...

public List<Item> getItems(Integer[] item_ids) {
    if(item_ids == null || item_ids.length ==0){
        return null;
    }
    List<Item> items = new ArrayList<Item>();
    for(Integer item_id : item_ids){
        Item d = itemMap.get(item_id);
        if( d !=null){
            items.add(d);
        }
    }
    return items;
}

【问题讨论】:

  • 投反对票并不意味着有人被冒犯了,这意味着他们认为您的问题“没有显示任何研究工作;不清楚或没有用”(来源:工具提示在downvote按钮上)。我猜有人投了反对票,因为您实际上并没有提出问题,所以它不清楚
  • 对不起,我的意思是“面面相觑”。我添加了我认为是隐含的确切问题,以防有人想投票重新开放。

标签: java arrays java-stream


【解决方案1】:

您可以简单地使用filtermap(这将推断类型)。

return Arrays.stream(item_ids)
    .filter(itemMap::containsKey)
    .map(itemMap::get)
    .collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    也可以使用,

    List<String> collect = Arrays.stream(item_ids)
                                         .map(itemMap::get)
                                         .filter(Objects::nonNull)
                                         .collect(Collectors.toList());
    

    【讨论】:

      猜你喜欢
      • 2021-07-19
      • 2021-04-06
      • 2016-01-13
      • 2020-02-17
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 2014-10-15
      • 1970-01-01
      相关资源
      最近更新 更多