Combining values with Java 8 streams
•
Java
If I have a list with integers, is there any way to build another list? If the header difference of the new list is lower than threashold, are integers added? I want to use Java 8 stream to solve this problem It should be similar to rxjava's scan operator
Example: 5,2,5,13 Threashold: 2 Result: 5,9,13 Intermediate results: 5 5,2 5,4 (2 and 2 summed) 5,9 (4 and 5 summed) 5,13
Solution
The sequential flow solution may be as follows:
List<Integer> result = Stream.of(5,13).collect(ArrayList::new,(list,n) -> { if(!list.isEmpty() && Math.abs(list.get(list.size()-1)-n) < 2) list.set(list.size()-1,list.get(list.size()-1)+n); else list.add(n); },(l1,l2) -> {throw new UnsupportedOperationException();}); System.out.println(result);
Although it doesn't look like a good old solution:
List<Integer> input = Arrays.asList(5,13); List<Integer> list = new ArrayList<>(); for(Integer n : input) { if(!list.isEmpty() && Math.abs(list.get(list.size()-1)-n) < 2) list.set(list.size()-1,list.get(list.size()-1)+n); else list.add(n); } System.out.println(list);
It seems that your problem is not related, so it cannot be easily parallelized For example, if the input is divided into two groups, such as (5,2), (2,13), it cannot be explained whether the first two items of the second group should be merged until the first group is processed Therefore, I cannot specify the correct combiner function
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码