我在ArrayList下面[P,a,y,P,a,l,I,n,d,i,a]
我想删除所有重复项,包括原始值。例如:“ P”是重复的。如果我使用set,它将删除重复项并显示一个“ P”。我想删除所有的“ P”。
我已经尝试过以下代码。但是只有在有一组字符的情况下,它才有效,
ArrayList<Character> unique = new ArrayList<Character>();
for (Character c : b) {
if (unique.contains(c)) {
unique.remove(c);
} else {
unique.add(c);
}
}
此代码验证并删除'P',但不删除'a'。因为“ a”列出了3 t
首先计算每个字符的出现次数,然后按出现次数过滤掉(仅出现一次)。
List<Character> input = Arrays.asList('P', 'a', 'y', 'P', 'a', 'l', 'I', 'n', 'd', 'i', 'a');
List<Character> collect = input.stream()
.collect(Collectors.groupingBy(p -> p, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(collect);
尝试一下:
List<Character> input = Arrays.asList('P', 'a', 'y', 'P', 'a', 'l', 'I', 'n');
List<Character> collect = input
.stream()
.distinct()
.collect(Collectors.toList());
尝试这种方法:
public static void main(String[] args) {
List<Character> unique = Arrays.asList('P', 'a', 'y', 'P', 'a', 'l', 'I', 'n', 'd', 'i', 'a');
List<Character> result = unique.stream().filter(i1 -> unique.stream().filter(i2 -> i1.equals(i2)).count() == 1).collect(Collectors.toList());
System.out.println(result);
}
输出为:[y, l, I, n, d, i]
我很高兴看到人们对Java感兴趣,希望您能获得所需的帮助。
在您的代码中,您的列表声明有问题。
请用列表替换ArrayList声明
如果您想计算不同字符
long uniqueCharactersCount = b.stream().distinct().count();
如果b是一个数组,请考虑将其包装到列表中