我已经尝试了与此主题相关的所有其他问题和答案,但我还没有成功。
我有一个专门排序的字符串列表,例如:["serviceT", "servicC", "serviceA", ... "serviceZ"]
。
我还有另一个同名 jar 文件的完整路径列表:
[“C:\Users\USER\projects ....\serviceB-1.0-SNAPSHOT.jar”...]
。这个列表是完全无序的。该列表是使用以下内容生成的:
servicesPaths = Files.walk(Paths.get(parentFolder))
.map(Path::toString)
.filter(path -> {
boolean flag = false;
for (String service : services)
if (path.endsWith(version + ".jar") && path.contains(service)) flag = true;
return flag;
})
.collect(Collectors.toList());
本质上,我只是给它一个父文件夹,它会返回包含service
的所有路径的列表。两个列表最终大小相同。我的意思是,每个服务
都有一个路径
。
我需要对 servicePath
列表进行排序,以便它与 services
有序列表的顺序相同。
我尝试过使用我能想到的所有排序/比较器方法,并且只能使用非常残酷的 for 循环使其工作:
List<String> temp = new ArrayList<>();
for (String service : services)
for (String path : servicesPaths)
if (path.indexOf(service) > 0)
temp.add(path);
还有其他合理的方法来对 servicePaths
列表进行排序吗?
最佳答案
一个非常简单的解决方案,但我认为它是合适的:
List<String> services = Arrays.asList("serviceA", "serviceC", "serviceB");
List<String> servicesPaths = Arrays.asList("serviceA-bla-bla", "serviceB-bla-bla", "serviceC-bla-bla");
List<String> sortedServices = servicesPaths.stream()
.sorted((a, b) -> Integer.compare(
services.indexOf(a.substring(0, a.indexOf("-"))),
services.indexOf(b.substring(0, b.indexOf("-")))))
.collect(Collectors.toList());
子字符串部分只是从路径中提取服务名称。如果您还有其他方法可以做到这一点,只需将其替换为其他方法即可。
另外,我会通过将比较函数存储在变量中来改进此代码片段:
Function<String, Integer> indexInServices = path -> services.indexOf(path.substring(0, path.indexOf("-")));
List<String> orderedServices = servicesPaths.stream()
.sorted(Comparator.comparing(indexInServices))
.collect(Collectors.toList());
关于java - 按包含原始子字符串的另一个列表对字符串列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45089309/