简体   繁体   中英

How to find the maximal value between every n elements in ArrayList?

How to find the maximal value between every n elements in ArrayList? I have a list filled with objects of this class.

public class NetworkMetric {

    private Instant eventDate;
    private Long inBytes;
    private Long outBytes;
    private Long inPcg;
    private Long outPcg;

}

I need to find the maximum value (between object fields) between every n elements in a given list.

var list = List.of(
    new NetworkMetric("instant",0L,2L,3L,4L),
    new NetworkMetric("instant0",1L,32L,33L,54L),
    new NetworkMetric("instant1",33L,2L,2223L,554L),
    new NetworkMetric("instant2",13L,444L,243L,5554L),
    new NetworkMetric("instant3",1L,2L,311L,4444L),
    new NetworkMetric("instant4",144L,112L,773L,544L),
    new NetworkMetric("instant5",10L,202L,773L,354L),
    new NetworkMetric("instant6",33L,362L,73L,4L),
    new NetworkMetric("instant7",13L,24L,63L,664L),
    new NetworkMetric("instant8",6L,12L,3333L,4L)

);

For example I need to find the maximum values in every 3 elements of the list. The list is sorted by Instant from earliest to latest. We have to go from the end of the list, looking for the maximum between 3 objects in each field. The result should be a list of new objects, where each object consists of an Instant of each n items and a maximum of the fields between the n items.

 new NetworkMetric("instant8",33L,362L,3333L,664L),
 new NetworkMetric("instant6",144L,362L,773L,544L),
 new NetworkMetric("instant4",144L,444L,773L,5554L),
 new NetworkMetric("instant2",33L,32L,2223L,5554L)

If there are not enough elements for n interval at the end, this interval is ignored

I don't get it.

The first new object contains field values from the last three list entries instant6, instant7 and instant8. The second new object contains field values from the list entries instant4, instant5 and instant6. That's already confusing to me, because instant7 is missing while instant6 is considered again.

The third new object contains field values from list entries instant2 and instant4. And the fourth new object contains values from list entries instant1 and instant2, but there is a larger value in one component.

Please explain in more details which elements are compared at which stage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM