java - 这是按 Java 集合中的键排序的最有效方法吗?
问题描述
有没有更有效的方法来实现这个结果。我本质上想先看看值Section
最长的getContextPath()
。
enum Section {
Provider("Provider", "com.app.provider"),
Container("Container", "com.app");
/**
* The key for this Section.
*/
private String key;
/**
* The context path for this Section.
*/
private String contextPath;
/**
* Create a new Section.
*
* @param key The Key for this section.
* @param contextPath The Context Path for this section.
*/
Section(String key, String contextPath) {
this.key = key;
this.contextPath = contextPath;
}
/**
* Retrieve the String representation of this Section.
*
* @return The String value.
*/
@SuppressWarnings("NullableProblems")
@Override
public String toString() {
return this.key;
}
/**
* Retrieve the Context Path for this Section.
*
* @return The Context Path.
*/
public String getContextPath()
{
return this.contextPath;
}
}
// Keep in mind that these may be dynamically loaded, and won't always be
// statically loaded like this.
private static final Map<Section, String> sectionLoggerIds = new HashMap<>() {{
put(Section.Container, "some.id");
put(Section.Provider, "some.other.id");
}};
/**
* Retrieve a Logger based on a Context.
*
* @param context The Context.
* @return The Logger
*/
public static Logger logger(Context context) {
// Create a TreeSet for sorting the values, and set it up
// to sort them longest first.
Set<Section> sectionSet = new TreeSet<>(new Comparator<Section>() {
@Override
public int compare(Section section1, Section section2) {
return Integer.compare(
section2.getContextPath().length(),
section1.getContextPath().length()
);
}
});
// Add all of the relevant Section objects.
sectionSet.addAll(sectionLoggerIds.keySet());
// Search the Sections, starting with the longest
// contextPath first.
for(Section section : sectionSet) {
if (context.getClass().getName().contains(section.getContextPath())) {
return getLogger(sectionLoggerIds.get(section));
}
}
return null;
}
解决方案
推荐阅读
- python - 将 Matplotlib Figure 转换为灰度和黑白 numpy 数组
- pine-script - 查找特定时期内的最高 MACD
- python - 需要帮助将 Windows 通知转换为 python 中的文本转语音
- java - MySql 查询动态创建的表
- c - 如何在c中将整数作为命令行参数传递?
- python - 从 CSV 转换为 Python DataFrame 中的分类数据
- python - 将新列添加到倒置二进制值的 ndarray | NumPy 数组 Python
- java - 无法构建 openfire-apns-plugin
- database - 如何通过最接近今天的数据查找记录
- c# - C#每次调用接口方法时添加自定义事件