Month: July 2015

  • Generating random mobile numbers with Java 8

    Generating random mobile numbers with Java 8

    In a previous post I gave a way of generating random test mobile numbers (Ofcom approved!) using Scala iterators.

    Now that Java 8 gives us lambdas and streams I thought I would see what those generators might look like in Java.

    Here’s the mobile generator:

    Supplier<String> mobileSupplier = () -> String.format("447700900%03d", ThreadLocalRandom.current().nextInt(999));

    Nice, still a one-liner.

    Generating pseudo MAC addresses is a little bit more trouble. This supplier uses another nested stream to generate the random hex array.

    Supplier<String> macSupplier = () -> ThreadLocalRandom.current().ints(6, 0, 255)
            .mapToObj(i -> String.format("%02x", i))
            .collect(Collectors.joining(":"));

    You use these Supplier functions with the static generate method of Stream. Because the generators create infinite streams we use limit to just get a few values. Eg:

    import java.util.concurrent.ThreadLocalRandom;
    import java.util.function.Supplier;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Generators {
    
        private static final Supplier<String> mobileSupplier = () -> String.format("447700900%03d", ThreadLocalRandom.current().nextInt(999));
    
        private static final Supplier<String> macSupplier = () -> ThreadLocalRandom.current().ints(6, 0, 255)
                .mapToObj(i -> String.format("%02x", i))
                .collect(Collectors.joining(":"));
    
        public static void main(String[] args) {
            System.out.println("Some mobile numbers:");
            Stream.generate(Generators.mobileSupplier)
                    .limit(5)
                    .forEach(System.out::println);
            System.out.println();
    
            System.out.println("Some (pseudo) mac addresses:");
            Stream.generate(Generators.macSupplier)
                    .limit(5)
                    .forEach(System.out::println);
        }
    }