How to sort an ArrayList with object using stream().sorted()

前端 未结 5 1594

I am having real trouble with using stream and sorted to sort my ArrayList and hope someone can help out. The code uses Croatian words, but I don\'t think that will be a pro

相关标签:
5条回答
  • 2021-01-13 09:05

    Below code is used for to sort the your Publikacija object type Arraylist on behalf of "getCijena"

    ' Collections.sort(data, new Comparator<Publikacija>() {
                public int compare(Publ`enter code here`ikacija s1, Publikacija s2) {
    
                    return s1.getCijena.compareTo(s2.getCijena);
                }
            });'
    
    0 讨论(0)
  • 2021-01-13 09:07

    You can also do it in that way:

    listaPublikacija.stream().sorted(Comparator.comparingDouble(Publikacija::getCijena));
    
    0 讨论(0)
  • 2021-01-13 09:20
    Publikacija[] sortedArray = listaPublikacija.stream()
       .sorted(Comparators.comparing(Publikacija::getCijena, Double::compareTo)
       .toArray();
    

    First method reference extracts the identifying key, second provides the compare function.

    0 讨论(0)
  • 2021-01-13 09:22
        Object[] sortirano = listaPublikacija.stream().sorted((s1, s2) -> Double.compare(s1.getCijena(), s2.getCijena())).toArray();
    

    this worked, ty for the answer

    0 讨论(0)
  • 2021-01-13 09:23

    You are not storing the results of the sorted array back to collection or array. Stream operations do not mutate the underlying collection:

        List<String> names = Arrays.asList("Katka", "Martin", "John");
    
        Object[] sortedNames = names.stream().sorted(String::compareTo).toArray();
    
        System.out.println("array: " + Arrays.toString(sortedNames));
    
    0 讨论(0)
提交回复
热议问题