Java实现在一个字符串集合中找出相同的内容

该代码片段使用Java实现了一个功能,从多个字符串列表中找出共同的单词,通过正则表达式提取单词,并计算交集。测试用例展示了在安全固定木台的上下文中找出共有的描述词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package org.jeecg;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 功能描述
 *
 * @author: yekongyu
 * @date: 2023年06月20日 15:38
 */


public class VerifyCheckTest {


    public static List<String> findCommonChars(List<String> strings) {
        if (strings == null || strings.isEmpty()) {
            return new ArrayList<>();
        }

        List<String> contents = new ArrayList<>();

        for (int i = 0; i < strings.size(); i++) {
            String string = strings.get(i);
            Set<String> commonContent = extractWords(string);

            for (int j = i + 1; j < strings.size(); j++) {
                String cont = strings.get(j);
                Set<String> intersection = calculateIntersection(commonContent, extractWords(cont));

                for (String com : intersection) {
                    if (com.length() > 1) {
                        contents.add(com);
                    }
                }
            }
        }

        // 去重并按长度降序排序
        Set<String> uniqueContents = new HashSet<>(contents);
        List<String> sortedContents = new ArrayList<>(uniqueContents);
        sortedContents.sort((a, b) -> b.length() - a.length());

        return sortedContents;
    }

    public static Set<String> extractWords(String string) {
        Set<String> words = new HashSet<>();
        Pattern pattern = Pattern.compile("\\b[\\p{L}\\p{N}_]+\\b");
        Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            words.add(matcher.group());
        }

        return words;
    }

    public static Set<String> calculateIntersection(Set<String> set1, Set<String> set2) {
        Set<String> intersection = new HashSet<>(set1);
        intersection.retainAll(set2);
        return intersection;
    }


    @Test
    public void test1(){
        List<String> contents = new ArrayList<>();
        contents.add("2)木台固定不牢,与建筑物表面有缝隙。木台直径在150mm及以下时,应用两条螺丝固定;木台直径在150mm以上时,应用三条螺丝成三角形固定。");
        contents.add("2、 木台固定不牢,与建筑物表面有缝隙,木台直径在75~150mm时,应用两条螺丝固定,木台直径在150mm以上时,应用三条螺丝成三角架固定。");
        contents.add("在确定成排灯具、吊扇的位置时,必须拉线,最好拉十字线。木台固定不牢,与建筑物表面有缝隙。木台直径在150mm及以下时,应用两条螺丝固定;台直径在150mm以上时,应用三条螺丝成三角形固定。");

        List<String> commonChars = findCommonChars(contents);

        for (String commonChar : commonChars) {
            System.out.println(commonChar);
        }

    }


}

运行效果
运行效果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值