Provide an iterator over the contents of two lists simultaneously?

前端 未结 11 2069
逝去的感伤
逝去的感伤 2020-12-03 04:45

Suppose I have this:

public class Unit {

    ...

    List mobileSuits;
    List pilots;

    ...
}
         


        
11条回答
  •  悲&欢浪女
    2020-12-03 05:30

    Came across this page trying to solve this issue, and turns out that there's a library out there that's already solved it using Java 8 streams (check out the Zip function).

    You can convert a list to a stream just by calling list.stream()

    https://github.com/poetix/protonpack

    Stream streamA = Stream.of("A", "B", "C");
    Stream streamB  = Stream.of("Apple", "Banana", "Carrot", "Doughnut");
    List zipped = StreamUtils.zip(streamA,
                                          streamB,
                                          (a, b) -> a + " is for " + b)
                                     .collect(Collectors.toList());
    
    assertThat(zipped,
               contains("A is for Apple", "B is for Banana", "C is for Carrot"));
    

提交回复
热议问题