Java 按枚举排序列表,然后按字母顺序排序
语言:Java 如何使用.getType()方法对ArrayList的内容进行排序,然后使用getName()按字母顺序进行排序 这是不同的,因为我从一个已经按字母顺序排列的列表开始,并且还想按类型排序 列表的一个示例:Java 按枚举排序列表,然后按字母顺序排序,java,Java,语言:Java 如何使用.getType()方法对ArrayList的内容进行排序,然后使用getName()按字母顺序进行排序 这是不同的,因为我从一个已经按字母顺序排列的列表开始,并且还想按类型排序 列表的一个示例: 0:Type=Grass Name=grassname示例此处 1:类型=石头名称=石头 2:类型=石头名称=石头名称 3:Type=Grass Name=stonewhere 清单应为: 0:Type=Grass Name=grassname示例此处 1:Type=Grass
0:Type=Grass Name=grassname示例此处
1:类型=石头名称=石头
2:类型=石头名称=石头名称
3:Type=Grass Name=stonewhere
清单应为:
0:Type=Grass Name=grassname示例此处
1:Type=Grass Name=stonewhere
2:类型=石头名称=石头
3:Type=Stone Name=stonewhere
感谢您的帮助
谢谢。公共类物品{
public class Item {
private String name;
private Type type;
public Item() {
}
public Item(String name, Type type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
@Override
public String toString() {
return "Item{" +
"name='" + name + '\'' +
", type=" + type +
'}';
}
}
public enum Type {
STONE,
GRASS
}
public class ItemComparator implements Comparator<Item> {
@Override
public int compare(Item o1, Item o2) {
String name1 = o1.getName();
String name2 = o2.getName();
Type type1 = o1.getType();
Type type2 = o2.getType();
int i = type1.name().compareTo(type2.name());
if (i != 0) return i;
i = name1.compareTo(name2);
return i;
}
}
public class Main {
public static void main(String[] args) {
Item item0 = new Item("StoneWhatever", Type.STONE);
Item item1 = new Item("StoneSomethingElse", Type.STONE);
Item item2 = new Item("StoneWhatever", Type.GRASS);
Item item3 = new Item("GrassNameExampleHere", Type.GRASS);
List<Item> itemList = new ArrayList<>();
itemList.add(item0);
itemList.add(item1);
itemList.add(item2);
itemList.add(item3);
Collections.sort(itemList, new ItemComparator());
for (Item item : itemList) {
System.out.println(item);
}
}
}
私有字符串名称;
私有类型;
公共项目(){
}
公共项(字符串名称、类型){
this.name=名称;
this.type=type;
}
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共类型getType(){
返回类型;
}
公共void集合类型(类型){
this.type=type;
}
@凌驾
公共字符串toString(){
返回“项目{”+
“name=”+name+“\”+
“,type=“+type”+
'}';
}
}
公共枚举类型{
石
草
}
公共类ItemComparator实现了Comparator{
@凌驾
公共整数比较(项目o1、项目o2){
字符串名称1=o1.getName();
字符串名称2=o2.getName();
类型type1=o1.getType();
Type type2=o2.getType();
int i=type1.name().compareTo(type2.name());
如果(i!=0)返回i;
i=名称1。与(名称2)相比;
返回i;
}
}
公共班机{
公共静态void main(字符串[]args){
项目0=新项目(“StoneWhather”,Type.STONE);
项目1=新项目(“StoneSomethingElse”,类型.STONE);
项目2=新项目(“Stonewhere”,类型为.GRASS);
item3=新项目(“GrassNameExampleHere”,Type.GRASS);
List itemList=new ArrayList();
itemList.add(item0);
项目列表。添加(项目1);
项目列表。添加(项目2);
项目列表。添加(项目3);
排序(itemList,newitemparator());
用于(项目:项目列表){
系统输出打印项次(项);
}
}
}
您能提供一些代码吗?通过编写自定义代码并调用。