例如我有这个列表:
myList = ['2','3','a','b','c','3','5','£','a','4',5','=']
如果相似的元素彼此相邻,我想将它们合并在一起。 所以我想最终得到一个新列表,如下所示:
newList = ['23', 'abc', '35', '£', 'a', '45', '=']
最佳答案
您需要定义一个方法来测试相似性,并使用它来将字符组合成字符串。
public static void main(String... args) throws Exception {
List<Character> myList = Arrays.asList('2', '3', 'a', 'b', 'c', '3', '5', '£', 'a', '4', '5', '=');
List<String> grouped = new ArrayList<>();
StringBuilder group = new StringBuilder();
String prevType = null;
for (Character ch : myList) {
String type = typeOf(ch);
if (prevType != null && type != prevType) {
grouped.add(group.toString());
group.setLength(0);
}
group.append(ch);
prevType = type;
}
grouped.add(group.toString());
System.out.println("myList= " + myList);
System.out.println("newList= " + grouped);
}
private static String typeOf(Character ch) {
return Character.isDigit(ch) ? "digit" :
Character.isAlphabetic(ch) ? "alpha" :
"other";
}
打印
myList= [2, 3, a, b, c, 3, 5, £, a, 4, 5, =]
newList= [23, abc, 35, £, a, 45, =]
关于java - 在java中合并列表中相似项目的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8714425/