0

I'm trying to learn more about comparators and streams and I was wondering the best solution to sort an array of objects with key values, sorting alphabetically by the value. Any help is hugely appreciated!

Example Array:
[
   {key: "93743743", value: "Mary Smith"},
   {key: "6624c357", value: "Tom Spitz"},
   {key: "03453459", value: "John Doe"},
   {key: "24623145", value: "Ernie Ball"}
]

Expected Result:
[
   {key: "24623145", value: "Ernie Ball"}
   {key: "03453459", value: "John Doe"},
   {key: "93743743", value: "Mary Smith"},
   {key: "6624c357", value: "Tom Spitz"},

]

Having a bit of trouble with the exact syntax using it in a stream (using a stream to subsequently filter and return an array of the names). Could also filter the array after if easier.

  • Does this answer your question? https://stackoverflow.com/questions/29567575/sort-map-by-value-using-lambdas-and-streams Or, similar questions: https://stackoverflow.com/search?q=%5Bjava%5D+sort+map+value+streams – Old Dog Programmer Apr 07 '23 at 21:33

1 Answers1

0

With an array of MyObject defined as follows:

record MyObject(String key, String value) {}

You can use Comparator.comparing with a method reference to sort it.

MyObject[] res = Arrays.stream(arr)
     .sorted(Comparator.comparing(MyObject::value)).toArray(MyObject[]::new);
// or your getter may be named as MyObject::getValue
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • See a working example [here](https://ato.pxeger.com/run?1=ZZHNTsMwDMfFcXsKq6cGjQjWbmOdOPB1QZo4lBvikHXZltE2leMWlalPwmUHeCUOPA3J1glNRJZiOT__7dgfn2tRie32q6TF2eXPybfKCo0ELspLUik_nXSLcpaqBJJUGANToXLYdDtt0JAge1VazSGzT35MqPLl8wsIXBrmyA7KROMcpvXjbC0TahF4lXUPWr8SaSkt3Vj8wO00EK5gk8u3v2xvHIxCZ14PvKnAGuJM0cpjPTjmhsN-mASDkeOedAZxoejdYbaGPcfweRAOrI0d_KBXOdxp-V-yHw77wUU4cNQ95krCjUhTjzWT475RGtv3NaKoDTeEUmS-_Qvjxg5Xzv1bnRUCBWnkyc61M_AP-VG0nwbjpHcS_p9yFNmGmKu20Ah-JRA0RK4eg7g2JDOuS-KFFaQ097VDm26zX2-75cO2fwE). – Unmitigated Apr 07 '23 at 21:32