You can create the list of sums in one line by mapping the streams (I did add line breaks for legibility):
//made some example lists
List<Float> list1 = Arrays.asList(new Float[]{1F, 2F, 3F});
List<Float> list2 = Arrays.asList(new Float[]{2F, 3F, 4F});
// Get the list with all the sums
List<Float> sums = list1.stream()
.map( f -> (list2.get(list1.lastIndexOf(f)) + f ) )
.collect(Collectors.toList());
// Get the index of the max pair
int maxIndex = sums.indexOf(sums.stream().max(Float::compareTo).get());
Just stream the first list, and .map
it (map is like a foreach but returns a result for each list item).
What's happening in the map:
for each item it finds the highest index for the current value f
in list 1. That'll be the index of the current item in the first list. Then it gets the value for this index in the second list. list2.get(list1.lastIndexOf(f))
. So now you add the current value f
to that. This way, for the full length of list 1 you are outputting the sum of the two values that share the same index.
Then you just need to .collect
them back into a list.
Finally to find the max index, I would take the exact same approach you did.