按多个属性对对象排序 [英] Sorting objects by multiple attributes

查看:100
本文介绍了按多个属性对对象排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做一些需要我按三个属性排序对象(软饮料)的东西 - name(str) color( str) volume(int)。我已经研究过,并找到了通过名称,颜色和体积分别订购它们的方法,但有没有办法在三个方面对它们进行订购?

I've been working on something that requires me to sort objects (Soft drinks) by three attributes - name (str), colour (str) and volume (int). I've researched around and found ways to order them by name and colour and volume separately, but is there a way to order them by all three?

我的意思是:例如,假设有四个SoftDrink对象:Fanta Orange 500,Coke Red 500,Coke Silver 500 Fanta Orange 400.

By which I mean: For example, say there are four SoftDrink objects: Fanta Orange 500, Coke Red 500, Coke Silver 500 Fanta Orange 400.

我正在寻找的输出将是:

The output I'm looking for would be:



  • 1)可乐红500

  • 2)可乐银500

  • 3)芬达橙400

  • 4)芬达橙500

  • 1) Coke Red 500
  • 2) Coke Silver 500
  • 3) Fanta Orange 400
  • 4) Fanta Orange 500

首先按名称排序,然后按颜色排序,然后按体积排序(升序)。

Sort by name first, then colour, then volume (ascending).

我目前使用三个比较器: nameComparator colourComparator volumeComparator ,但每个对象只按名称排序,然后按颜色排序,然后按体积排序。是否可以使用Comparator根据多个属性进行排序?

I'm using three Comparators currently: nameComparator, colourComparator, and volumeComparator, but each of them sorts the objects by name only, then by colour only, then by volume only. Is it possible to sort according to multiple attributes with Comparator?

推荐答案

尝试这样的事情:

drinks.sort(
      Comparator.comparing(Drink::getName).thenComparing(Drink::getColour).thenComparing(Drink::getVolume)
    );

请记住为您的属性设置getter( getName getColour 等)。这就是您所需要的,无需任何自定义比较器或任何东西。

Remember to have getters for your attributes (getName, getColour etc.). This is all you need, no need for any custom comparators or anything.

这篇关于按多个属性对对象排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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