关于该主题,我已经尝试过其他所有问答方式,但是我没有设法使其有效。
我有一个特别排序的字符串列表,例如:["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
的所有路径的列表。两个列表的大小相同。我的意思是,每个service
都只有一个path
。我需要排序
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());