Java 两个基元类型流到一个对流

Java 两个基元类型流到一个对流,java,java-stream,Java,Java Stream,我有两个收藏: List<String> names = ... List<Long> counts = ... 目前,这是我的解决方案: List<Foo> foos = IntStream.range(0, names.size()) .mapToObj(i -> new Foo(names.get(i), counts.get(i))) .co

我有两个收藏:

List<String> names = ...
List<Long> counts = ...
目前,这是我的解决方案:

List<Foo> foos = IntStream.range(0, names.size())
                          .mapToObj(i -> new Foo(names.get(i), counts.get(i)))
                          .collect(Collectors.toList());
List foos=IntStream.range(0,names.size())
.mapToObj(i->newfoo(name.get(i),counts.get(i)))
.collect(Collectors.toList());

我的问题:还有其他方法来配对和收集Foo对象吗

您的解决方案依赖于两个集合的相同大小,因此我们应该关注这一点。让我们暂时搁置Java流API,因为除了使用带索引的
IntStream
range之外,没有其他方法可以同时遍历两个集合。简单地说,Java流API不适合这个用例

您需要确保调用时不会抛出任何
IndexOutOfBoundsException
。我喜欢两种方式:

  • 具有共轭条件的两个迭代器:

    List<Foo> fooList = new ArrayList<>();
    while (namesIterator.hasNext() && countsIterator.hasNext()) {
        Foo foo = new Foo(namesIterator.next(), countsIterator.next());
        fooList.add(foo);
    }
    
    List-doulist=new-ArrayList();
    while(namesIterator.hasNext()&&countsIterator.hasNext()){
    Foo Foo=new Foo(namesIterator.next(),countsIterator.next());
    傻瓜。添加(foo);
    }
    
  • 用于索引达到两个列表大小下限的每次迭代:

    int bound = Math.min(names.size(), counts.size());
    List<Foo> fooList = new ArrayList<>();
    for (int i=0; i<bound; i++) {
        Foo foo = new Foo(names.get(i), counts.get(i);
        fooList.add(foo);
    }
    
    int-bound=Math.min(name.size(),counts.size());
    列表列表=新的ArrayList();
    对于(int i=0;i新Foo(name.get(i)、counts.get(i)))
    .collect(Collectors.toList());
    
  • 也有专门用于压缩的外部库,例如来自Guava或来自jOOλ的方法。压缩机制在各个库中几乎相同


    Java Stream API的当前设计不适合它。

    请将您的问题发布在代码审查上。@RavindraRanwala-这真是个糟糕的建议。代码审查不是关于如何做一些不同的事情的问题。当然,还有其他方法,例如,您可以使用循环。关于流API,这是最简单的解决方案。既然它能工作,而且你没有任何实际的问题,就不用费心去想其他的选择了。看你做得对吧。。您还可以进一步使用所有人都喜欢您的代码的库。有用链接
    List<Foo> fooList = new ArrayList<>();
    while (namesIterator.hasNext() && countsIterator.hasNext()) {
        Foo foo = new Foo(namesIterator.next(), countsIterator.next());
        fooList.add(foo);
    }
    
    int bound = Math.min(names.size(), counts.size());
    List<Foo> fooList = new ArrayList<>();
    for (int i=0; i<bound; i++) {
        Foo foo = new Foo(names.get(i), counts.get(i);
        fooList.add(foo);
    }
    
    List<Foo> fooList = IntStream.rangeClosed(0, Math.min(names.size(), counts.size()))
                                 .mapToObj(i -> new Foo(names.get(i), counts.get(i)))
                                 .collect(Collectors.toList());