如何使用 stream().sorted() 对带有对象的 ArrayList 进行排序 [英] How to sort an ArrayList with object using stream().sorted()

查看:104
本文介绍了如何使用 stream().sorted() 对带有对象的 ArrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用流和排序对我的 ArrayList 进行排序时遇到了真正的麻烦,希望有人能提供帮助.代码使用克罗地亚语单词,但我认为对于理解我意思的人来说这不会成为问题.

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 problem for someone who understands what I mean.

这是数组列表

ArrayList<Publikacija> listaPublikacija = new ArrayList<>();

listaPublikacija.add(prvaKnjiga);
listaPublikacija.add(drugaKnjiga);
listaPublikacija.add(prviCasopis);
listaPublikacija.add(drugiCasopis);

在我的作业中,我应该通过双倍的 getCijena() 对上面的这些对象进行排序.

In my assignment I am supposed to sort these objects above by getCijena() which is double.

这是我得到的最好的,但它仍然没有按应有的方式对其进行排序...

This is the best I got and it still doesn't sort it as it should...

listaPublikacija.stream().sorted((s1, s2) -> Double.compare(s1.getCijena(), s2.getCijena()));

感谢任何形式的帮助或建议......我已经以不同的方式进行了排序,但是有必要通过流中的排序方法对其进行排序......

Any kind of help or advice appreciated... I already made the sort in different ways, but it is neccessary to sort it via the sorted method in stream...

为了更容易理解上面的问题,我将在下面发布课程脚本:

I'll post the class script below for easier understanding of the question above:

public Publikacija(String nazivKnjige, int godinaIzdanja, int brojStr, VrstaPublikacije vrstaPub, double cijenaPoStr, double cijena){
this.nazivKnjige= nazivKnjige;
this.godinaIzdanja = godinaIzdanja;
this.brojStr = brojStr;
this.vrstaPub = vrstaPub;
this.cijenaPoStr = cijenaPoStr;
if(getClass().equals(Casopis.class)){this.cijena= Casopis.CIJENA_PO_PRIMJERKU;}
else this.cijena = provjeraCijene(cijena(brojStr,vrstaPub,cijenaPoStr).doubleValue());

推荐答案

您没有将排序数组的结果存储回集合或数组. 流操作不会改变底层集合:

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));

这篇关于如何使用 stream().sorted() 对带有对象的 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆