代码之家  ›  专栏  ›  技术社区  ›  Aymen Kanzari

根据另一个列表字符串对列表字符串排序

  •  -1
  • Aymen Kanzari  · 技术社区  · 6 年前

    我有一个 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());
    

    我想根据list arrayOfString的元素对列表组织进行排序

    例子:

    • str=服务提供商测试1 32722 21211

    count 将等于2,因为 str

    • str=SP recherche自动完成7897788 7897788

    计数 包含“7”(消除重复字符)

    然后根据

    2 回复  |  直到 6 年前
        1
  •  0
  •   chaffee    6 年前

    作为练习,我根据提示{@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;
    }
    
        2
  •  0
  •   Oleg Cherednik    6 年前
    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 整理你的收藏。