gpt4 book ai didi

java - 使用自定义参数对列表进行排序

转载 作者:行者123 更新时间:2023-11-29 10:18:24 27 4
gpt4 key购买 nike

Here is my code :

import java.util.List;

import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.bc.filter.SearchRequestService;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.search.SearchException;
import com.atlassian.jira.issue.search.SearchProvider;
import com.atlassian.jira.issue.search.SearchRequest;
import com.atlassian.jira.issue.search.SearchResults;
import com.atlassian.jira.web.bean.PagerFilter;


class IssueTest{

String id;
String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}

public IssueTest(String id,String type)
{
this.id = id;
this.type = type;

}


}


public class test {

/**
* @param args
*/

static List<IssueTest> issues;


public static void main(String[] args) {
// TODO Auto-generated method stub

test t = new test();


}

public test ()
{

IssueTest i = new IssueTest("B-1", "bug");
issues.add(i);
IssueTest j = new IssueTest("S-1", "story");
issues.add(j);
IssueTest k = new IssueTest("T-1", "task");
issues.add(k);
IssueTest l = new IssueTest("T-2", "task");
issues.add(l);
IssueTest m = new IssueTest("E-1", "epic");
issues.add(m);
IssueTest n = new IssueTest("E-2", "epic");
issues.add(n);
IssueTest o = new IssueTest("T-3", "task");
issues.add(o);
IssueTest p = new IssueTest("S-2", "story");
issues.add(p);
IssueTest q = new IssueTest("B-2", "bug");
issues.add(q);
IssueTest r = new IssueTest("B-3", "bug");
issues.add(r);

}


}

I want to sort this list according to the "type" . I want all objects in the order of - tasks then bugs then story then epic

最佳答案

您将需要编写自定义 Comparator 来实现该排序。不幸的是,如果没有第三方库,这会有点复杂……特别是如果您不使用 Java 7。

Comparator<IssueTest> comparator = new Comparator<IssueTest>() {
private int getStringPosition(String str) {
if(str.equals("task")) {
return 0;
} else if (str.equals("bug")) {
return 1;
} else if (str.equals("story")) {
return 2;
} else if (str.equals("epic")) {
return 3;
} else {
throw new AssertionError();
}
}
public int compare(IssueTest a, IssueTest b) {
return getStringPosition(a.getType()) - getStringPosition(b.getType());
}
};
Collections.sort(list, comparator);

不过,如果您使用枚举而不是字符串类型,这会容易得多。

如果您可以使用第三方库,使用 Guava 可能会更简单一些:

Ordering<String> typeOrdering = Ordering.explicit("task", "bug", "story", "epic");
Ordering<IssueTest> issueTestOrdering =
typeOrdering.onResultOf(new Function<IssueTest, String>() {
public String apply(IssueTest it) {return it.getType(); }
});
Collections.sort(list, issueTestOrdering);

(披露:我为 Guava 做出贡献。)

关于java - 使用自定义参数对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11759437/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com