直接怼代码,刚好碰到了这种需求,也是想了可久,其实想想也还是挺简单的
public static void main(String[] args) { // 原始字符串集合 List<String> originalList = new ArrayList<>(); originalList.add("Hello"); originalList.add("World"); originalList.add("Android"); originalList.add("Development"); // 获取字符串的最大长度 int maxLength = 0; for (String str : originalList) { maxLength = Math.max(maxLength, str.length()); } // 使用循环和数组操作获取每个位置的字符集合 List<String> charListAtIndex = new ArrayList<>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < maxLength; i++) { charListAtIndex.clear(); for (String str : originalList) { if (i < str.length()) { sb.setLength(0); // 清空 StringBuilder sb.append(str.charAt(i)); // 添加当前字符 charListAtIndex.add(sb.toString()); // 将 StringBuilder 转换为 String 并添加到列表中 } } System.out.println("Character List at Index " + i + ": " + charListAtIndex); } }
结果:
Character List at Index 0: [H, W, A, D]
Character List at Index 1: [e, o, n, e]
Character List at Index 2: [l, r, d, v]
Character List at Index 3: [l, o, o, l]
Character List at Index 4: [o, r, i, p]
Character List at Index 5: [m, e]
Character List at Index 6: [n, t]