3

I am trying to sort an arraylist that has custom objects. I want to sort my arraylist based on a property inside the object.

Below is my code:

List<Object[]> search = qry1.getResultList();

Below is my output:

"searchresults" = ArrayList<E> 
elementData=Object[33]
[0] = Object[10] 
    [0] = "Dog"
    [1] = "Animal"
    [2] = "Carnivorous"
[1] = Object[10]
    [0] = "Lion"
    [1] = "Animal"
    [2] = "Carnivorous"
[2] = Object[10]
    [0] = "Cow"
    [1] = "Animal"
    [2] = "Herbivorous"
[3] = Object[10]
    [0] = "Buffalo"
    [1] = "Animal"
    [2] = "Herbivorous"

Now i want to sort the result based on the animal name(Buffalo, Dog, Lion)

I tried using java 8 function but didnt work. Also tried using comparator but didnt work:

search.stream().sorted(comp1, comp2);

Please guide.

sTg
  • 4,313
  • 16
  • 68
  • 115
  • How is this duplicate.. Pls understand i dont have a pojo class here as in the question which has been marked for the reference. – sTg Nov 07 '16 at 13:55
  • @Schirish The solution is to use a custom comarator - just as it is answered in the other question. You don't have a POJO class, but this does not matter - you can implement a custom comparator for object arrays. So to speak `Object[]` is your POJO class. – lexicore Nov 07 '16 at 14:18
  • as we can see people there have done object.getDate for eg what can i do in my case? – sTg Nov 07 '16 at 14:28
  • 1
    You want to sort a collection of `Object[]` over first entries, right. So write a `Comparator` and compare `value[0]`. – lexicore Nov 07 '16 at 14:30
  • Thanks @lexicore :). It helped . Kayaman : The logic said by lexicore was nowhere present in the question marked for reference. – sTg Nov 07 '16 at 14:46
  • From my POV it is a duplicate. "Write a custom comparator" is the given answer. You could have adapted it to `Object[]`. – lexicore Nov 07 '16 at 14:54

0 Answers0