Search for the 1st free "index" using Java threads

I need to find the 1st free index on my file system with a stream of names as a source.

Consider the list: ["New2", "New4", "New0", "New1", ...] The 1st unused index of them will be 3.

int index = 0;
try (IntStream indexes = names.stream()
    .filter(name -> name.startsWith("New"))
    .mapToInt(Integer::parseInt)
    .distinct()
    .sorted())
{
    // I was thinking about making possible indexes stream, removing existig ones from try-with-resource block, and getting .min().
    IntStream.rangeClosed(0, 10)... // Idk what to do.
}

I ask someone to help me find the right syntax for my idea or suggest a better solution.

+4
source share
3 answers

The most effective way is to collect in BitSet:

int first = names.stream()
    .filter(name -> name.startsWith("New"))
    .mapToInt(s -> Integer.parseInt(s.substring(3)))
    .collect(BitSet::new, BitSet::set, BitSet::or).nextClearBit(0);

, . , "" . 0 , + 1, , .

+7

:

  • 0
  • ,

, :

List<String> names = Arrays.asList("New2", "New4", "New0", "New1");
Set<Integer> taken = names.stream()
    .map(s -> s.replaceAll("\\D+", ""))
    .map(Integer::parseInt)
    .collect(Collectors.toSet());
int first = IntStream.range(0, names.size())
    .filter(index -> !taken.contains(index))
    .findFirst()
    .orElse(names.size());
+4

, , 63 ...

    private static int firstMissing(List<Long> input) {
        if (!input.contains(0L)) {
           return 0;
        }

        long firstMissing = Long.lowestOneBit(~input.stream().reduce(1L, (i, j) -> i | 1L << j));

        int result = 0;
        while (firstMissing != 0) {
           ++result;
           firstMissing = firstMissing >> 1;
        }

        return result - 1;
    }

, @Holger (+1 ), BitSet.

0

Source: https://habr.com/ru/post/1664347/


All Articles