如何从 ArrayList (Java) 中的字符串数组打印字符串的组合 [英] How to print combinations of Strings from String arrays in an ArrayList (Java)

查看:29
本文介绍了如何从 ArrayList (Java) 中的字符串数组打印字符串的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 ArrayList 列表,其中包含一些我需要获取组合的 String[].

So I have an ArrayList<String[]> list which contains some String[] that I need to get the combinations of.

所以如果列表包含 A = {a,b,c} 和 B = {d,e,f} 我想打印

So if list contained A = {a,b,c} and B = {d,e,f} I want to print

ad,ae,af,bd,be,bf,cd,ce,cf

我只是无法理解我将如何拥有一个固定数组然后获取另一个数组,以便我可以遍历它.

I am just having trouble seeing how I would have one fixed array then get the other so I can iterate through that.

为了澄清我正在尝试为 N String[] 执行此操作,因此我无法获得第 0 个和第 1 个元素.

To clarify I am trying to do this for N String[] so I cant just get the 0th and 1st element.

推荐答案

迭代两个数组并在每一步创建新的字符串组合.毕竟只是以某种方式打印组合.

Iterate over two arrays and on each step make new string combination. After all just print combinations in some way.

    List<String[]> input = ...;
    Set<String> allCombinations = new HashSet<>();
    for (int i = 0; i < input.size() - 1; i++) {
        for (int j = i + 1; j < input.size(); j++) {
            allCombinations.addAll(twoArraysCombinations(input.get(i), input.get(j)));
        }
    }
    // print allCombinations


private static Set<String> twoArraysCombinations(String[] first, String[] second) {
    Set<String> result = new HashSet<>();
    for (String f : first) {
        for (String s : second) {
            result.add(f + s);
        }
    }
    return result;
}

这篇关于如何从 ArrayList (Java) 中的字符串数组打印字符串的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆