Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

java - Calculate the differences in a List in a functional way

I have a list of absolute values (for example: 10, 50, 30), which I'd like to transform in a functional way to a list of differences between these numbers. So, given an input as 10, 50, 30, I'd like the outcome to be: 40, -20.

For context: my current implementation is just a for loop which keeps track of the previous value, calculates the difference, and adds it a new list, but I was wondering how this can be solved in a more functional way? (I'm using Kotlin, but a solution in Java would be fine too)

question from:https://stackoverflow.com/questions/65929744/calculate-the-differences-in-a-list-in-a-functional-way

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use zipWithNext.

You pass in a lambda taking 2 parameters. zipWithNext will go through the list and pass each pair of elements to your lambda. To compute the difference, simply subtract:

val list = listOf(10, 50, 30)
val result = list.zipWithNext { a, b -> b - a }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...