0

I've a list of elements into a list. Those elements are returned ordered into a Object[]. In that array the first element is a Document, the second is a DocumentRow. I'm grouping all rows that belong to the same document together using the groupingBy function.

List<Object[]> rows = documentRowRepository.rowsExportSTS(from, until);

Map<Document, List<DocumentRow>> rowsGroupedByDocument = 
    rows.stream()
        .map(r -> (DocumentRow) r[1])
        .collect(Collectors.groupingBy(r -> r.getDocument()));

I see that resulting Map is not sorted by Document.id. Is there a way to do that without add more operation considering that the original List is already sorted?

marstran
  • 26,413
  • 5
  • 61
  • 67
drenda
  • 5,846
  • 11
  • 68
  • 141
  • 1
    `r -> (DocumentRow) r[1]` is not retrieving the first element. Indexing in Java starts at 0. – marstran Oct 08 '19 at 17:32
  • r[1] is the row. In first position there is the Document – drenda Oct 08 '19 at 17:33
  • Oh, nevermind. It gets a row, not a Document. – marstran Oct 08 '19 at 17:33
  • 2
    if you want to maintain insertion order then accumulate the result of the grouping into a `LinkedHashMap`. `.collect(Collectors.groupingBy(r -> r.getDocument(), LinkedHashMap::new, Collectors.toList()));`. if you want to sort after grouping see the duplicate or many of the duplicates on the site. – Ousmane D. Oct 08 '19 at 17:37
  • @OusmaneD. unfortunately I'm working with a Object[]. I can't use r.getDocument() – drenda Oct 08 '19 at 17:46
  • @OusmaneD. your solution works fine. Do you want provide an answer so I can confirm it? Thanks – drenda Oct 08 '19 at 18:03
  • @drenda glad it worked for you. enjoy!. no need for me to post an answer. – Ousmane D. Oct 08 '19 at 18:04

0 Answers0