1

I have list with the following structure:

Class Data {
   String id;
   String type;
   String reference;
}

The reference here may or may not be null. I have the following set of data in a list:

[
{
id:"1",
type:"A",
reference:"3"
},
{
id:"2",
type:"B",
reference:null
},
{
id:"3",
type:"C",
reference:"1"
}
]

I want it be sorted based on reference - 1 references 3 and 3 references 1. Such items have to be grouped together as below:

[
{
id:"1",
type:"A",
reference:"3"
},
{
id:"3",
type:"C",
reference:"1"
},
{
id:"2",
type:"B",
reference:null
}
]
  • 3
    there are multiple solutions [based on the comparable interface, the comparator or a lambda as explained in this answer](https://stackoverflow.com/a/2784576/4014509). – Sebastian S Aug 13 '18 at 18:43
  • `List list = ..; list.sort(Comparator.nullsLast(Comparator.comparing(d -> d.reference)));` – zapl Aug 13 '18 at 18:45
  • This isn't "sorting" by reference; it's creating a linked list based on the reference->id mapping, right? Can you give more example data? – Mick Mnemonic Aug 13 '18 at 18:49

0 Answers0