0

Say I have two lists of equal size [1, 2, 3, 4, ...] and [a, b, c, d, ...]. Is there a way I make a map with streams that maps 1 to a, 2 to b, 3 to c, and so on without using lambda functions or nested functions?

I would use map and pass in a function, but this passed-in function can only take 1 argument and I need both pieces of information to map the elements to each other.

IntStream(1, list1.size()).stream().map(this.&combineListsFunction).collect...

combineListsFunction can only use the information from the stream, but I need both lists for the function to work.

emilyl
  • 11
  • 2

1 Answers1

1

You can transpose both lists (which will give you a list of tuples and then create the map from it with collectEntries() (which takes exactly this). E.g.:

def l1 = [1,2,3]
def l2 = ["a","b","c"]

assert [(1): "a", (2): "b", (3): "c"] == [l1,l2].transpose().collectEntries()
cfrick
  • 35,203
  • 6
  • 56
  • 68
  • Is there a more general way to solve the problem of using `map` but the function passed in needs multiple pieces of information? I simplified my actual question, but did not anticipate that the simplified question would have its own specific answer. – emilyl Jun 19 '19 at 19:04
  • AFAIK no. `map` takes a `Function` and so you have to provide a function with one argument, that would take e.g. a list and destructure yourself. Or you capture something from the outside (provide a closure to map. E.g. https://stackoverflow.com/questions/49388245/java-transposing-a-list-of-list-using-streams). Or go hunt for the missing `zip` function https://stackoverflow.com/questions/17640754/zipping-streams-using-jdk8-with-lambda-java-util-stream-streams-zip – cfrick Jun 19 '19 at 19:18