How to convert a List of objects into a Map by considering duplicated keys and store them in sorted order?

This program converts a List of objects into a Map while handling duplicate keys and preserving sorted order, using the four-argument overload of Collectors.toMap().

Code Example:

public class TestNotes {

    public static void main(String[] args) {

        List<Notes> noteLst = new ArrayList<>();
        noteLst.add(new Notes(1, "note1", 11));
        noteLst.add(new Notes(2, "note2", 22));
        noteLst.add(new Notes(3, "note3", 33));
        noteLst.add(new Notes(4, "note4", 44));
        noteLst.add(new Notes(5, "note5", 55));
        noteLst.add(new Notes(6, "note4", 66));

        Map<String, Long> notesRecords = noteLst.stream()
                .sorted(Comparator.comparingLong(Notes::getTagId).reversed())
                .collect(Collectors.toMap(
                        Notes::getTagName,
                        Notes::getTagId,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new));

        System.out.println("Notes : " + notesRecords);
    }
}

The merge function (oldValue, newValue) -> oldValue keeps the first entry when two notes share the same tag name (here, note4 appears twice), and LinkedHashMap::new preserves the sorted order produced by the stream.