Search code examples
javaspring-bootlambdajava-stream

Remove small compose-identifier from List with Lambdas


I need to remove specifics IDs from a list.

Explaining myself better, I have a list of Documents that contains compound Strings, which are identifiers. These identifiers are made up of a pair of Integers separated by a "-".

The idea is to remove from that list of identifiers all those that contain the same first part of the String AND keep only the largest of them. That is, if I have a list of Documents with the following output:

"documentId": "521-1"
"documentId": "521-2"
"documentId": "32-2"
"documentId": "112-6"
"documentId": "112-11"
"documentId": "112-2"

The result should be:

"documentId": "521-2"
"documentId": "112-11"
"documentId": "32-2"

I have tried to do it with streams but I don't see the way. I go through the list but since they are compound identifiers I don't know how to make the comparisons nor how to keep the smallest of them.

My pseudo-code, which does not work:

    object.getDocuments().stream().reduce((a, b)->{                     
if(a.getFirstPart().equals(b.getFirstPart())){
        //Then I should remove the small secondPart                 
    } return b;});

Solution

  • Here's one way. Note that it isn't robust against invalid data.

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class Test {
        public static void main(String[] args) {
    
            String[] ids = {"521-1",
                    "521-2",
                    "32-2",
                    "112-6",
                    "112-11",
                    "112-2"
            };
            List<String> result = Arrays.stream(ids).collect(Collectors.toMap(
                    s -> s.split("-")[0], s -> Integer.parseInt(s.split("-")[1]), Math::max
            )).entrySet().stream().map(e -> e.getKey() + "-" + e.getValue()).collect(Collectors.toList());
            System.out.println(result);
        }
    }