I want to return a string consisting of those digits (in ascending order) that do not appear in any of the argument numbers. I don't know how this should be done, but I would like to use the long as a comparator to find out the missing digits in IntStream.
For example, if numeros = [1201, 23045], I must return "6789"
My code:
public static String digitosQueNoEstanEn(List<Long> numeros)
{
long n = 1234567890;
IntStream numStream = numeros.stream()
.map(c -> c.toString())
.flatMapToInt(c -> c.chars())
.distinct();
There are many solutions to this problem, one of which is a simple set removal. You essentially want to remove all used digits from the set of valid digits, and store the result as a String
. That can be done with the following:
public static String digitosQueNoEstanEn(List<Long> numeros) {
Set<Integer> usedDigits = numeros.stream()
.map(String::valueOf)
.flatMapToInt(String::chars)
.map(c -> Character.digit(c, 10))
.boxed()
.collect(Collectors.toSet());
return IntStream.range(0, 10)
.filter(i -> !usedDigits.contains(i))
.sorted()
.mapToObj(Integer::toString)
.collect(Collectors.joining());
}
When invoked with your example of [1201L, 23045L]
, the output is what you expect:
6789
Andy Turner also mentioned that using a BitSet
may be a viable solution. If you choose to use one, your solution may look like the following:
public static String digitosQueNoEstanEn(List<Long> numeros) {
BitSet bitSet = BitSet.valueOf(new long[] { 0b0011_1111_1111 });
numeros.stream()
.map(String::valueOf)
.flatMapToInt(String::chars)
.map(c -> Character.digit(c, 10))
.forEach(bitSet::clear);
return bitSet.stream()
.sorted()
.mapToObj(Integer::toString)
.collect(Collectors.joining());
}
Here is what I came up with.
public static String digitosQueNoEstanEn(List<Long> numeros) {
String digits = "0123456789";
return numeros.stream()
.flatMap(numero->Arrays.stream(Long.toString(numero).split("")))
.distinct()
.reduce(digits, (dgts,d)->dgts.contains(d) ? dgts.replace(d,"") : dgts);
}
List<Long> numeros = List.of(1201L, 23045L);
digitosQueNoEstanEn(numeros);
System.out.println(result);
6789
Basically I flatten the list of supplied numbers to digits and then just remove them in a reducing operation. What is left are the digits that were not in the original numbers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.