我有一个List<String>
,其值如下:
static String input = "pro or 7";
List<String> arrayOfString = Arrays.asList(input.toLowerCase().split("\\s+"));
我还有另一个字符串列表:
static List<String> organizations = Arrays.asList(
"Service Provider organisation 3 01254 25742", // count=3
"Service Provider test 2 132455 132455", // count=1
"Service Provider organisation 2 78900 6521", // count=3
"VOYAGES ANSELMINO 30876168300025 382510022", // count=1
"Service Provider test 1 32722 21211", // count=2
"SP recherche autocomplete 7897788 7897788") // count=1
.stream().map(String::toLowerCase)
.collect(Collectors.toList());
我想根据列表arrayOfString的元素对列表组织进行排序
示例:
count
等于2,因为str
包含'pro'和'7'
count
等于1,因为str
包含'7'(消除重复字符)
然后根据count
的结果对列表组织进行排序
答案 0 :(得分:0)
我根据提示{@Lokesh Give}来实施它,作为练习。 您可以参考它。
List<String> organizations = Arrays.asList(
"Service Provider organisation 3 01254 25742", // count=3
"Service Provider test 2 132455 132455", // count=1
"Service Provider organisation 2 78900 6521", // count=3
"VOYAGES ANSELMINO 30876168300025 382510022", // count=1
"Service Provider test 1 32722 21211", // count=2
"SP recherche autocomplete 7897788 7897788") // count=1
.stream().map(String::toLowerCase).sorted(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return getCountMeetCondition(o2) - getCountMeetCondition(o1);
}
}).collect(Collectors.toList());
private static int getCountMeetCondition(String s) {
int count = 0;
for (int i = 0; i < arrayOfString.size(); i++) {
if (s.contains(arrayOfString.get(i))) {
count++;
}
}
return count;
}
答案 1 :(得分:0)
final Function<String, Set<String>> split = str -> new HashSet<>(Arrays.asList(str.toLowerCase().split("\\s+")));
final Set<String> keys = split.apply("pro or 7");
final Function<String, Integer> getCount = str -> {
int count = 0;
str = str.toLowerCase();
for (String key : keys)
if (str.contains(key))
count++;
return count;
};
final Comparator<String> comparator = Comparator.comparingInt(getCount::apply);
您可以使用此comparator
对收藏进行排序。