Java 按名称对ArrayList项排序

Java 按名称对ArrayList项排序,java,arraylist,Java,Arraylist,我正在尝试根据要在特定索引上的项的名称重新排列ArrayList 我目前的名单如下: "SL" "TA" "VP" "SP" "PR" 我想将它们重新排列为: "SL" "SP" "TA" "PR" "VP" 但基于名称,而不是索引 我试过这个: for (int i=0; i< list.size(); i++){ if (list.get(i).getCategoryName().equals("SL")){ orderedDummyJSONModelLis

我正在尝试根据要在特定索引上的项的名称重新排列ArrayList

我目前的名单如下:

"SL"
"TA"
"VP"
"SP"
"PR"
我想将它们重新排列为:

"SL"
"SP"
"TA"
"PR"
"VP"
但基于名称,而不是索引

我试过这个:

for (int i=0; i< list.size(); i++){
    if (list.get(i).getCategoryName().equals("SL")){
        orderedDummyJSONModelList.add(list.get(i));
    }
}
for (int i=0; i< list.size(); i++){
    if (list.get(i).getCategoryName().equals("SP")){
        orderedDummyJSONModelList.add(list.get(i));
    }
}
for (int i=0; i< list.size(); i++){
    if (list.get(i).getCategoryName().equals("TA")){
        orderedDummyJSONModelList.add(list.get(i));
    }
}
for (int i=0; i< list.size(); i++){
    if (list.get(i).getCategoryName().equals("PR")){
        orderedDummyJSONModelList.add(list.get(i));
    }
}
for (int i=0; i< list.size(); i++){
    if (list.get(i).getCategoryName().equals("VP")){
       orderedDummyJSONModelList.add(list.get(i));
    }
}

这同样有效。有什么想法吗?

你可以使用
Collection.Sort
方法作为
Collection.Sort(list)
,因为
list
是一个
list
你会没事的。但如果您想实现一个新的比较器:

Collections.sort(list, new NameComparator());

class NameComparator implements Comparator<String> { //You can use classes
    @Override
    public int compare(String a, String b) { //You can use classes
        return a.compareTo(b); 
    }
}
Collections.sort(list,newnameparator());
类名Comparator实现Comparator{//您可以使用类
@凌驾
公共int比较(字符串a、字符串b){//您可以使用类
返回a.compareTo(b);
}
}
编辑:

您可以根据需要定义类比较器:

class ClassComparator implements Comparator<YourClass> { //You can use classes
    @Override
    public int compare(YourClass a, YourClass b) { //You can use classes
        return a.name.compareTo(b.name); 
    }
}
class ClassComparator实现Comparator{//您可以使用类
@凌驾
公共int比较(你的类a,你的类b){//你可以使用类
返回a.name.compareTo(b.name);
}
}

这里的关键是:你需要明确你的需求

换句话说:当然可以在列表中存储的对象之间来回移动。但是:您可能希望以编程方式执行该操作

换句话说:正确的方法是使用内置的集合排序机制,但提供一个自定义比较器

意思:你最好找到一个算法来定义如何从

“SL” “TA” “副总裁” “SP” “公关”

“SL” “SP” “TA” “公关” “副总裁”

该算法应该应用到比较器实现中

重点是:首先,您有一些
列表。X对象提供了某种方法来检索这里显示的字符串。因此,您必须创建一个对X值起作用的
比较器
;并使用一些平均值来获取这些字符串值;根据这一点,你可以决定X1是否比某个X2对象更重要

  • 使用hashmap存储所有字符串的权重(hashmap的值越高,表示该字符串在最终列表中出现的时间越晚)
  • 使用Hashmap,以便以后也可以对其他字符串进行扩展。以后会更容易增强
  • 最后,使用一个定制的比较器来完成
  • 所需设置:

           List<String> listOfStrings = Arrays.asList("SL", "TA", "VP", "SP", "PR");
    
            HashMap<String, Integer> sortOrder = new HashMap<>();
            sortOrder.put("SL", 0);
            sortOrder.put("TA", 1);
            sortOrder.put("VP", 2);
            sortOrder.put("SP", 3);
            sortOrder.put("PR", 4);
    
            List<String> sortedList = listOfStrings.stream().sorted((a, b) -> {
                return Integer.compare(sortOrder.get(a), sortOrder.get(b));
            }).collect(Collectors.toList());
    
            System.out.println(sortedList);
    
            Collections.sort(listOfStrings, (a, b) -> {
                return Integer.compare(sortOrder.get(a), sortOrder.get(b));
            });
    OR
            listOfStrings.sort((a, b) -> {
                return Integer.compare(sortOrder.get(a), sortOrder.get(b));
            });
    
            System.out.println(listOfStrings);
    
    输出

    [SL, TA, VP, SP, PR]
    

    这里有一个针对您的问题的答案,只针对给定的输出。如果
    列表
    包含任何其他内容,这可能会中断您的订购,因为没有关于如何订购的规则,并且
    PR
    只是随机出现在最后

    public static void main(String[] args) {
        List<String> justSomeNoRuleOrderingWithARandomPRInside = new ArrayList<String>();
        justSomeNoRuleOrderingWithARandomPRInside.add("SL");
        justSomeNoRuleOrderingWithARandomPRInside.add("TA");
        justSomeNoRuleOrderingWithARandomPRInside.add("VP");
        justSomeNoRuleOrderingWithARandomPRInside.add("SP");
        justSomeNoRuleOrderingWithARandomPRInside.add("PR");
        java.util.Collections.sort(justSomeNoRuleOrderingWithARandomPRInside, new NameComparator());
        for(String s : justSomeNoRuleOrderingWithARandomPRInside) {
            System.out.println(s);
        }
    }
    
    static class NameComparator implements Comparator<String> { //You can use classes
        @Override
        public int compare(String a, String b) { //You can use classes
            // Lets just add a T in front to make the VP appear at the end 
            // after TA, because why not
            if (a.equals("PR")) {
                a = "T"+a;
            } else if(b.equals("PR")) {
                b = "T"+b;
            }
            return a.compareTo(b);
        }
    }
    
    但老实说,这个解决方案是垃圾,如果没有任何关于如何订购的明确规则,@GhostCat试图解释,一旦你改变任何东西,这个解决方案就注定要失败。

    这个怎么样

    // define the order
    List<String> ORDER = Arrays.asList("SL", "SP", "TA", "PR", "VP");
    
    List<MyObject> list = ...
    list.sort((a, b) -> {
        // lamba syntax for a Comparator<MyObject>
        return Integer.compare(ORDER.indexOf(a.getString()), ORDER.indexOf(b.getString());
    });
    
    //定义顺序
    列表顺序=数组。asList(“SL”、“SP”、“TA”、“PR”、“VP”);
    列表=。。。
    列表.排序((a,b)->{
    //比较器的lamba语法
    返回Integer.compare(ORDER.indexOf(a.getString()),ORDER.indexOf(b.getString());
    });
    

    请注意,这会将订单列表中未定义的任何字符串放在排序列表的开头。这可能是可以接受的,也可能是不可以接受的-可能需要检查MyObject.getString()的结果是否仅显示有效字符串(即订单的成员).

    您可以使用
    LinkedHashMap
    构建索引映射。这将用于查找使用项目类别名称进行排序的顺序

    项目排序 结果
    您可以创建一个维护位置的映射。当您遍历无序列表时,只需获取该字符串值的位置并插入到新数组(而不是arraylist)中,然后,如果需要,您可以稍后将该数组转换为arraylist。 示例代码:

    Map<String,Integer> map = new HashMap<>(); //you can may be loop through and make this map
    map.put("SL", 0);
    map.put("SP", 1);
    map.put("TA",2);
    map.put("PR",3);
    map.put("VP",3);
    List<String> list1 // your unordered list with values in random order
    String[] newArr =  new String[list1.size()];
    for(String strName: list1){
        int position  = map.get(strName);
        arr[position] = strName;
    }
    //newArr has ordered result.
    
    Map Map=newhashmap();//您可以循环并生成此映射
    地图放置(“SL”,0);
    地图放置(“SP”,1);
    地图放置(“TA”,2);
    地图放置(“PR”,3);
    地图放置(“VP”,3);
    List list1//无序列表中的值按随机顺序排列
    String[]newArr=新字符串[list1.size()];
    for(字符串strName:list1){
    int position=map.get(strName);
    arr[位置]=strName;
    }
    //newArr已命令结果。
    
    您可以定义这样的帮助器方法:

    public static int get(String name) {
        switch (name) {
        case "SL":
            return 1;
        case "SP":
            return 2;
        case "TA":
            return 3;
        case "PR":
            return 4;
        case "VP":
            return 5;
        default:
            return 6;
        }
    }
    
    在你的主要方法中写下如下内容:

    ArrayList<String> al = new ArrayList<>();
    al.add("SL");
    al.add("TA");
    al.add("VP");
    al.add("SP");
    al.add("PR");
    Collections.sort(al, (o1, o2) -> return get(o1) - get(o2); );
    al.forEach((s) -> System.out.println(s));
    
    ArrayList al=new ArrayList();
    al.添加(“SL”);
    al.添加(“TA”);
    新增(“VP”);
    al.添加(“SP”);
    新增(“PR”);
    Collections.sort(al,(o1,o2)->返回get(o1)-get(o2);
    al.forEach((s)->System.out.println(s));
    
    你可以编写一个自定义的
    Comperator
    并用这个
    Comperator
    调用
    Collections#sort
    你能提供一个代码示例吗?排序是基于什么的?它不是字母的。不,它不是字母的。它实际上是包含字符串的对象,我希望重新排列是基于这些字符串的当然,这不难做到,但你如何定义排序?默认情况下,字符串是按字典顺序排序的,但这会产生不同的结果。嗯,你不能做
    String>另一个字符串
    。它不是字符串。它包含字符串的对象你的示例代码甚至不会编译;我不知道你为什么认为你可以在Str上使用>正在对对象进行排序。我猜这将使用自然排序顺序进行排序。但问题是要按照用户定义的方式进行排序。是的,没错。但问题是列表中包含具有这些字符串的对象。这不是字符串列表。您可以粘贴代码吗?这对我有用,我已经粘贴了输出。@Parator我猜他确实使用了对象con获取排序器上的
    字符串
    。获取
    ,而不是
    字符串
    @KevinEsche。它不是strings@patriarch然后,作为
    whatEverObject.getCategoryName()访问
    字符串
    并使用它来代替编剧处理弦乐?适应它应该不难。@precitrar Like
    import java.util.Comparator;
    
    public class ItemComparator implements Comparator<Item> {
        private IndexMap indexMap;
    
        public IndexMap getIndexMap() {
            return indexMap;
        }
    
        public void setIndexMap(IndexMap indexMap) {
            this.indexMap = indexMap;
        }
    
        public ItemComparator(IndexMap indexMap) {
            this.indexMap = indexMap;
        }
    
        @Override
        public int compare(Item itemA, Item itemB) {
            if (itemB == null) return -1;
            if (itemA == null) return 1;
            if (itemA.equals(itemB)) return 0;
    
            Integer valA = indexMap.get(itemA.getCategoryName());
            Integer valB = indexMap.get(itemB.getCategoryName());
    
            if (valB == null) return -1;
            if (valA == null) return 1;
    
            return valA.compareTo(valB);
        }
    }
    
    import java.util.LinkedHashMap;
    
    public class IndexMap extends LinkedHashMap<String, Integer> {
        private static final long serialVersionUID = 7891095847767899453L;
    
        public IndexMap(String... indicies) {
            super();
    
            if (indicies != null) {
                for (int i = 0; i < indicies.length; i++) {
                    this.put(indicies[i], new Integer(i));
                }
            }
        }
    }
    
    public class Item {
        private String categoryName;
    
        public Item(String categoryName) {
            super();
            this.categoryName = categoryName;
        }
    
        public String getCategoryName() {
            return categoryName;
        }
    
        public void setCategoryName(String categoryName) {
            this.categoryName = categoryName;
        }
    
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((categoryName == null) ? 0 : categoryName.hashCode());
            return result;
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj) return true;
            if (obj == null) return false;
            if (getClass() != obj.getClass()) return false;
            Item other = (Item) obj;
            if (categoryName == null) {
                if (other.categoryName != null) return false;
            } else if (!categoryName.equals(other.categoryName)) return false;
            return true;
        }
    
        @Override
        public String toString() {
            return String.format("Item { \"categoryName\" : \"%s\" }", categoryName);
        }
    }
    
    Item { "categoryName" : "SL" }
    Item { "categoryName" : "SP" }
    Item { "categoryName" : "TA" }
    Item { "categoryName" : "PR" }
    Item { "categoryName" : "VP" }
    
    Map<String,Integer> map = new HashMap<>(); //you can may be loop through and make this map
    map.put("SL", 0);
    map.put("SP", 1);
    map.put("TA",2);
    map.put("PR",3);
    map.put("VP",3);
    List<String> list1 // your unordered list with values in random order
    String[] newArr =  new String[list1.size()];
    for(String strName: list1){
        int position  = map.get(strName);
        arr[position] = strName;
    }
    //newArr has ordered result.
    
    public static int get(String name) {
        switch (name) {
        case "SL":
            return 1;
        case "SP":
            return 2;
        case "TA":
            return 3;
        case "PR":
            return 4;
        case "VP":
            return 5;
        default:
            return 6;
        }
    }
    
    ArrayList<String> al = new ArrayList<>();
    al.add("SL");
    al.add("TA");
    al.add("VP");
    al.add("SP");
    al.add("PR");
    Collections.sort(al, (o1, o2) -> return get(o1) - get(o2); );
    al.forEach((s) -> System.out.println(s));