lzha190 2013-04-02 18:44
浏览 886
已采纳

如何将 List<List<String>>中包含相同元素的List进行搜索重组

假设一个List里面包含多个List:
<"apple", "banana">,<"ball", "pen"> <"apple", "orange">, <"grape", "orange">,<"paper","ruler">,<"ink","pen">
如何将每个List进行重复比对,并将含有相同元素的List合并,最后形成一个新的List>:
<"apple","banana","orange","grape">,,<"paper","ruler">

也可理解为:"A=B","C=D","A=E","F=E","G=H","I=D" =>
"A=B=E=F","C=D=I","G=H"

请诸位不吝指教,谢谢!

  • 写回答

3条回答 默认 最新

  • clxy大叔 2013-04-02 21:36
    关注

    没考虑性能,仅供参考。

    [code="java"]
    public static void main(String[] args) {

    List<Set<String>> lists = new ArrayList<Set<String>>() {
        {
            add(new HashSet<String>(Arrays.asList("apple", "banana")));
            add(new HashSet<String>(Arrays.asList("ball", "pen")));
            add(new HashSet<String>(Arrays.asList("apple", "orange")));
            add(new HashSet<String>(Arrays.asList("grape", "orange")));
            add(new HashSet<String>(Arrays.asList("paper", "ruler")));
            add(new HashSet<String>(Arrays.asList("ink", "pen")));
        }
    };
    
    System.out.println(merge(lists));
    

    }

    public static List> merge(List> lists) {

    List<Set<String>> result = new ArrayList<Set<String>>();
    
    Map<String, Set<String>> map = new HashMap<String, Set<String>>();
    for (Set<String> list : lists) {
    
        // 寻找类似的列表。
        Set<String> simList = null;
        for (Entry<String, Set<String>> e : map.entrySet()) {
            if (list.contains(e.getKey())) {
                simList = e.getValue();
                simList.addAll(list);// 合并类似。
                break;
            }
        }
    
        // 没找到类似。
        if (simList == null) {
            result.add(list);// 结果中加入引用。
            simList = list;
        }
    
        // 已经合并过了,所以不再区分。
        for (String s : list) {
            map.put(s, simList);
        }
    }
    
    return result;
    

    }
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?