动态列表中字符的每种组合

问题描述

我坚持逻辑。我有一个自由文本下拉菜单用户可以自由输入最多5个字符。现在,每个字符都有与之关联的Unicode重音字符。我为与字符关联的列表生成unicode字符。现在,我想使用列表中的字符生成所有可能的组合。因为列表是动态生成的,所以我有点卡住了。我如何知道应该首先迭代哪个列表?下面是我的代码

//example String key="za";
if (key!=null) {
    List<Character> characList = key.chars()
                                    .mapToObj(c -> (char) c)
                                    .collect(Collectors.toList());//[z,a]
    List<List<String>> mainList = new ArrayList<List<String>>();
    for (Character characterObj:characList) {
        List<String> subList = new ArrayList<String>();
        Collection<String> charColl = unicodeMap.getCollection(characterObj.toString());
        subList = new ArrayList(charColl);//first iteration we get [ż,ź,ž] second iteration we get [à,á,â,ã,ä,å,ą,ă,ā]
        mainList.add(subList);//[[ż,ž],[à,ā]]
    }
}

现在,我想从String生成[[ż,ā]]的组合。 String可能是azstu等。如何进行迭代,以便它将处理输入的String的关联中的所有组合。请告知。

示例字符串中所需的输出:-

żà
żá
żâ
żã
żä
żå
żą
żă
żā
.
.
.

解决方法

一种可以递归生成字符串的方法。通过索引遍历角色的收集列表,并循环访问每个子列表。

List<String> genr(List<List<String>> list,int index,String now) {
    if (index >= list.size()) {
      return Arrays.asList(now);
    }
    List<String> subList = list.get(index);
    List<String> res = new ArrayList<>();
    for (String value : subList) {
      res.addAll(genr(list,index + 1,now + value));
    }
    return res;
  }

打来电话

List<List<String>> mainList = new ArrayList<List<String>>();
mainList.add(Arrays.asList("ż","ź","ž"));
mainList.add(Arrays.asList("à","á","â","ã","ä","å","ą","ă","ā"));
List<String> data = genr(mainList,"");

输出: [żà,żá,żâ,żã,żä,żå,żą,żă,żā,źà,źá,źâ,źã,źä,źå,źą,źă,źā,žà,žá,žâ,žã,žä,žå,žą,žă,žā]

演示here