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

末鹿安然 提交于 2019-12-01 05:20:59

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));
    Object[] sortirano = listaPublikacija.stream().sorted((s1, s2) -> Double.compare(s1.getCijena(), s2.getCijena())).toArray();

this worked, ty for the answer

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);
            }
        });'
Publikacija[] sortedArray = listaPublikacija.stream()
   .sorted(Comparators.comparing(Publikacija::getCijena, Double::compareTo)
   .toArray();

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!