给定一个String列表,有时我们不得不对所有项目进行排序,除了少数必须放在顶部或底部的项目,
List<String> profiles = Arrays.asList(new String[] {
"Y-Profile", "X-Profile", "Default", "A-Profile", "B-Profile"
});
List<String> sortedProfiles = profiles.stream().sorted((o1, o2)->o1.compareTo(o2)).
collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
带有默认字符串比较的当前输出如下,
sortedProfiles ==> [A-Profile, B-Profile, Default, X-Profile, Y-Profile]
Run Code Online (Sandbox Code Playgroud)
所需的输出如下,由于列表大小是动态的,并且可能在一段时间内变大,因此在Java中没有太多迭代或过滤的最佳方式是什么
sortedProfiles ==> [Default, A-Profile, B-Profile, X-Profile, Y-Profile]
Run Code Online (Sandbox Code Playgroud)
您需要实现一个比简单的更智能的比较器o1.compareTo(o2)。您可能最终会遇到这样的事情(虽然不一定是最有效的):
final String defaultVal = "Default";
List<String> sortedProfiles = profiles.stream().sorted(
(o1, o2) -> defaultVal.equals(o1) && defaultVal.equals(o2)
? 0
: (defaultVal .equals(o1)
? -1
: (defaultVal .equals(o2) ? 1 : o1.compareTo(o2)))
).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)