问题描述
我在使用流时遇到了麻烦,并对我的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
This is the ArrayList
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()使用对象对ArrayList进行排序.sorted()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!