我有这样的输入
Online Add-on 3 GB 2015
Online Add-on 1.5 GB 2015
Online Add-on 12 GB 2015
Online Add-on 6 GB
Online Add-on 375 MB 2015
Online Add-on 750 MB 2014我已经尝试过白体排序,它在这个链接中给出了输出,如下所示。
Online Add-on 1.5 GB 2015
Online Add-on 3 GB 2015
Online Add-on 6 GB
Online Add-on 12 GB 2015
Online Add-on 375 MB 2015
Online Add-on 750 MB 2014但是,为了获得更好的人类可读性,我需要如下所示的输出,如果年份存在,那么根据年份,较低的MB必须优先,然后更低的GB。
Online Add-on 750 MB 2014
Online Add-on 375 MB 2015
Online Add-on 6 GB
Online Add-on 1.5 GB 2015
Online Add-on 3 GB 2015
Online Add-on 12 GB 2015用Java做这个有什么办法吗?
发布于 2017-01-20 08:12:47
首先,以规范的方式格式化信息,为此定义一种格式:"Online Add-on 750 MB 2014" like "frefix size define“。
然后为它定义一个类(在下面的示例中是Capac)
震级可以是Enum (例子中的单位)。正确重写hashcode和equ。
然后用这些Capac对象创建一个列表,然后用一个预定义的比较器对其进行排序,使用双准则,第一个按大小排序,然后按大小排序。
示例:
public class Capac {
public static void main(String[] args) {
final String arr[] = { "Online Add-on 750 MB 2014", "Online Add-on 375 MB 2015", "Online Add-on 1.5 GB 2015",
"Online Add-on 3 GB 2015", "Online Add-on 6 GB 2015", "Online Add-on 12 GB 2015" };
final List<Capac> myList = new ArrayList<>();
for (final String string : arr) {
myList.add(new Capac(string));
}
System.out.println(myList);
// sort
Collections.sort(myList, new Comparator<Capac>() {
@Override
public int compare(Capac o1, Capac o2) {
if (o1.unit == o2.unit) {
return Double.compare(o1.size, o2.size);
} else {
return Integer.compare(o1.unit.ordinal(), o2.unit.ordinal());
}
}
});
System.out.println(myList);
}
private final double size;
private final int year;
private final Unit unit;
private final String prefix;
public Capac(String ss) {
final String[] rr = ss.split(" ");
prefix = rr[0] + " " + rr[1];
size = Double.parseDouble(rr[2]);
unit = Unit.valueOf(rr[3]);
year = Integer.parseInt(rr[4]);
}
@Override
public String toString() {
return prefix + " " + size + " " + unit + " " + year;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((prefix == null) ? 0 : prefix.hashCode());
long temp;
temp = Double.doubleToLongBits(size);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((unit == null) ? 0 : unit.hashCode());
result = prime * result + year;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Capac other = (Capac) obj;
if (prefix == null) {
if (other.prefix != null)
return false;
} else if (!prefix.equals(other.prefix))
return false;
if (Double.doubleToLongBits(size) != Double.doubleToLongBits(other.size))
return false;
if (unit != other.unit)
return false;
if (year != other.year)
return false;
return true;
}
}
enum Unit {
KB, MB, GB, TB
}被淘汰的人看起来像
2014年在线添加750.0 MB,2015年在线添加375.0 MB,2015年在线添加1.5GB,在线附加3.0GB 2015年,在线附加6.0GB 2015年,在线附加12.0GB 2015年
和
2015年在线加载项375.0 MB,2014年在线添加750.0 MB,2015年在线添加1.5GB,在线附加3.0GB 2015年,在线附加6.0GB 2015年,在线附加12.0GB 2015年
https://stackoverflow.com/questions/41757249
复制相似问题