Skip to content

Instantly share code, notes, and snippets.

@paulojeronimo
Created February 6, 2018 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulojeronimo/7f73ab2d9b816931e920bb96bf2dde35 to your computer and use it in GitHub Desktop.
Save paulojeronimo/7f73ab2d9b816931e920bb96bf2dde35 to your computer and use it in GitHub Desktop.
CPF em Java 8
import java.util.stream.IntStream;
import java.util.concurrent.atomic.AtomicInteger;
public class CPF {
public static IntStream reverseRangeClosed(int from, int to) {
return IntStream.rangeClosed(from, to).map(i -> to - i + from);
}
private static int calcDV(final char[] cpf, final int dv_pos) {
AtomicInteger a = new AtomicInteger();
int dv = reverseRangeClosed(2, dv_pos).map(i -> i * (cpf[a.getAndIncrement()] - 48)).sum() % 11;
return dv < 2 ? 0 : 11 - dv;
}
public static String calculateCPFDigits(String cpf) {
if (cpf != null) {
if (!cpf.matches("\\d+")) {
throw new IllegalArgumentException("O CPF informado não contém apenas dígitos");
} else if (cpf.length() >= 1 && cpf.length() < 9) {
return calculateCPFDigits(String.format("%9s", cpf).replace(' ', '0'));
} else if (cpf.length() == 9) {
cpf = cpf + calcDV(cpf.toCharArray(), 10);
return cpf + calcDV(cpf.toCharArray(), 11);
}
throw new IllegalArgumentException("O número de dígitos no CPF informado é superior a 9");
}
throw new IllegalArgumentException("O CPF informado é nulo");
}
public static void main (String args[]){
String cpf;
if (args.length > 0) {
cpf = args[0];
} else {
System.out.println("Informe os primeiros dígitos do CPF (até 9)");
return;
}
try {
System.out.println("CPF completo: " + calculateCPFDigits(cpf));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment