根据行中的单词作为键对行进行排序 [英] Sorting Lines Based on words in them as keys
问题描述
Odrer ID Descrption Type
Envelope K205 Green Paper >>>>String Line with space in between
Box J556 Yellow Thermocol >>>>String Line with space in between
Envelope L142 White Plastic >>>>String Line with space in between
我有一张类似上面的表格,我必须提供对表格进行排序的选项 基于列名称的数据,例如按顺序排序",按类型排序" 请给我建议最好的想法,以实现这一点在Java中...表行是带有字符串 分隔每对情侣的空间..
I have a table something like above and I have to provide options sort the data based on the column name, like "sort by Order", "Sort By Type" something like that plz suggest me the best ideas to achieve this in Java... The table rows are strings with space separating each touple..
推荐答案
将表中的每一行表示为具有顺序,id,描述和类型属性的对象.将每个对象添加到列表等集合中.然后,您可以创建不同的比较器,例如OrderComparator
和TypeComparator
,以分别根据顺序或类型对集合进行排序.
Represent each row in your table as an object with order, id, description and type attributes. Add each object to a collection such as a list. You can then create different comparators such as an OrderComparator
and a TypeComparator
to sort the collection based on order or type respectively.
例如,这是您的数据类的外观:
For example, here is what your data class might look like:
public class Data{
private final String order;
private final String id;
private final String description;
private final String type;
public Data(String order, String id, String description, String type) {
this.order=order;
this.id=id;
this.description=description;
this.type=type;
}
/** getter methods here **/
}
现在,您将它们添加到列表中,并使用特定的比较器对其进行排序:
Now, you would add them to a list and use a specific comparator to sort it:
//add data to a list
List<Data> list = new ArrayList<Data>();
list.add(new Data("Envelope","K205","Green","Paper"));
list.add(new Data("Box","J556","Yellow","Thermocol"));
list.add(new Data("Envelope","L142","White","Plastic"));
//create a comparator to sort by type
Comparator<Data> typeComparator = new Comparator<Data>() {
@Override
public int compare(Data o1, Data o2) {
return o1.getType().compareTo(o2.getType());
}
};
//sort the list
Collections.sort(list, typeComparator);
这篇关于根据行中的单词作为键对行进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!