加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java 8 Stream,按条件添加一个元素列出很多时间;

发布时间:2020-12-15 04:26:31 所属栏目:Java 来源:网络整理
导读:我有这样的行↓从列表中获取确切的元素,但我想多次添加它使用某种类型的数组,如“for”与计数器 list.stream().filter(x - x.getUserID() == user.getUserID()).collect(Collectors.toList());list.stream().map(o - new Object[] { (Object) o }).collect(C
我有这样的行↓从列表中获取确切的元素,但我想多次添加它使用某种类型的数组,如“for”与计数器

list.stream().filter(x -> x.getUserID() == user.getUserID()).collect(Collectors.toList());
list.stream().map(o -> new Object[] { (Object) o }).collect(Collectors.toList();

我有类似的代码,但我不想使用双:

List<Object[]> tmp = new ArrayList<Object[]>();
for (Iterator<?> iterator = tests.getTestData().iterator(); iterator.hasNext();) {
    Object objects = iterator.next();
    //should have condition like id=id
    for (int i = 0; i < t.getInvocationCount(it); i++) {
        tmp.add(new Object[] { objects });
    }
}

使用流可以满足条件的多个元素?

编辑:

*tests.getTestData() -> returns List
**t.getInvocationCount -> returns int [t is not important cause it is generic]

在通知中我只需要arry中的多个元素

FOR arry TO arry=END DO:
  IF arry[i] IS statment=true DO:
    FOR 0 TO outsideCounter_i DO:
      tempArry.add(arry[i])

其中*是arry而**是outsideCounter

如果statment使用stream,我想要多元素.
如果仍不清楚请添加评论.

我读到了关于nCopies的内容并且它很酷,但我可以在流内使用它吗?

解决方法

您可以使用IntStream作为用于复制元素的索引.

像这样的东西应该工作(我不完全确定你的两个代码片段是如何相关的,所以我可能得到了错误的名字):

List<Object[]> tmp =
    tests.getTestData().stream()
        .filter(x -> x.getUserID() == user.getUserID())  // not sure about this
                                                         // part,since it's not
                                                         // clear if the elements 
                                                         // of the input 
                                                         // Iterable have a 
                                                         // getUserID method
        .flatMap (x -> IntStream.range(0,t.getInvocationCount(it)).mapToObj(i -> x))
        .map(o -> new Object[] {o})
        .collect (Collectors.toList());

正如aioobe评论的那样,Collections.nCopies方法在这里很有用:

List<Object[]> tmp =
    tests.getTestData().stream()
        .filter(x -> x.getUserID() == user.getUserID())  // not sure about this
                                                         // part,since it's not
                                                         // clear if the elements 
                                                         // of the input 
                                                         // Iterable have a 
                                                         // getUserID method
        .flatMap (o -> Collections.nCopies(t.getInvocationCount(it),o).stream())
        .map (o -> new Object[] {o})
        .collect (Collectors.toList());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读