简体   繁体   中英

Rearrange the List based on one its value in Java

Authoring an Java method which takes List as parameter(MasterList) and returns another list(ExpectedList).

MasterList: 
{ 
    (ID :abc123, Count: 20),
    (ID :abc122, Count: 19),
    (ID :abc122, Count: 20),
    (ID :abc122, Count: 18),
    (ID :abc121, Count: 21),
    (ID :abc120, Count: 21),
    (ID :abc120, Count: 20)
}

Each object in List have two variables:

  1. ID (String)
  2. Count (Number)

The logic which I'm trying to achieve is: when the MasterList has more than one object where ID is same then consider only particular object whose count is greater. Means ID: abc122 has 3 objects, so I'll consider only (ID:abc122, Count: 20), because Count is higher among objects whose ID:abc122. At the end the method should return

ExpectedList:
    {
        (ID :abc123, Count: 20),
        (ID :abc122, Count: 20),
        (ID :abc121, Count: 21),
        (ID :abc120, Count: 21)
    }

Stream over your list and collect your objects grouping by ID and mapping to the object with max count using Collectors.maxBy to get a Map<String,Optional<MyObject>> . Stream over the values unwrap the optional and collect to list:

List<MyObject> result = 

list.stream()
    .collect(
            Collectors.groupingBy(
                    MyObject::getId, Collectors.maxBy(Comparator.comparing(MyObject::getCount))))
    .values()
    .stream()
    .map(Optional::get)
    .collect(Collectors.toList());

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