Certificación Java SE 8 Programmer I
Certificación Java SE 8 Programmer I
Certificación oficial:
● Java SE 8 Programmer I (1Z0-808)
Versiones de Java
Java SE (JSE) - Java Core Java EE (J2EE) - Java advanced
Java Standard Edition used to develop Java Enterprise Edition designed for enterprise and server applications.
desktop and web applications and Requires an application server to deploy and run.
basic web services. Doesn’t requiere
an application server to run. ● JPA - Java Persistence API
● WebApplications: API Java Servlets, JSP Java Server Pages, HTML, CSS.
● JDBC - Java Database Produces WAR file.
Connectivity ● EJB Enterprise JavaBeans. Produces JAR file.
● JavaFX, Swing, AWT (UI) ● EAR file: JAR + WAR.
● JMS - Java Message Service
● JNDI - Java Naming and Directory Interface
● JTA - Java Transaction API
● JAXP, JAX-WS, JAX-RPC - Java API for XML
JVM Frame: A new stack frame is created for every method invocation and destroyed when its execution completes. Each frame
contains a local variables array, a return value, operand stack and a Current Class Constant Pool reference. The stack is small and
managed automatically. The local variable array stores only primitive variables and references, while objects are stored on the heap.
JVM Heap: memory zone that stores dynamically created objects and arrays during runtime. It’s a larger memory region shared among
all threads. The Garbage collection (GC) frees unused memory in the heap. To support garbage collection the heap is divided into three
sections:
● Young Generation: Often split between Eden and Survivor. New objects and arrays are created into the young generation.
Minor garbage collection will operate in the young generation. Objects, that are still alive, will be moved from the eden space to
the survivor space.
● Old Generation (also called Tenured Generation). Major garbage collection, which typically causes the application threads to
pause, will move objects between generations. Objects, that are still alive, will be moved from the young generation to the old
(tenured) generation.
● Permanent Generation: is collected every time the old generation is collected. They are both collected when either becomes
full. From Java 8, replaced with Metaspace.
Metaspace: Starting from Java 8, Metaspace replaces the old PermGen (Permanent Generation). It holds class metadata (name, fields,
methods, constants, static methods). It dynamically re-sizes itself (up to the max limit of your machine memory) unlike the older
PermGen memory space which needed to be specified with a fixed size.
Clases en Java
Clase JAVA: es una plantilla (template) que define la forma de un objeto, agrupa atributos y métodos.
public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ⏺
default ✔ ✔ ⏺ ⏺
private ✔ ⏺ ⏺ ⏺
A partir de Java 9 (pendiente por desarrollar el tema)
Accesibilidad por medio de módulos:
● Public para todos
● Public solo a módulos amigos
● Public solo dentro de un módulo
● Además de Protected, Package y Private
module hello.world { //nombre module java.base{
exports com.example.hello; //paquetes expuestos exports java.lang;
requires java.base; //dependencias con otros módulos ...
} }
Es un paradigma de programación basado en clases (atributos y funciones) reutilizables y objetos. Permite que el código sea
reutilizable, organizado y fácil de mantener. Sus 4 pilares son: PAEI
Abstraction
Abstraction shows only useful data by providing only the most necessary details.
Es la exposición de los datos de un objeto proporcionando únicamente los detalles más necesarios y útiles de un objeto.
Supone una extensión a la encapsulación.
Encapsulation
Encapsulation is used to restrict direct access to attributes and methods of a
class by using access modifiers.
Consiste en ocultar atributos de un objeto de manera que solo se pueda cambiar mediante operaciones definidas en ese
objeto
Inheritance
Inheritance is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
La herencia es un mecanismo que permite la definición de una Clase Hija como extensión de una Clase Padre mediante la
palabra extends con el fin de reutilizar código.
Java permite múltiples niveles de herencia pero no la herencia múltiple, es decir una clase sólo puede heredar directamente
de una clase ascendiente. Todo lo que es común a ambas clases está en la Clase Padre, mientras lo específico, queda restringido a
las Clases Hijas. Solo se heredan los métodos y atributos públicos, default y protected.
Los constructores no se heredan pero pueden ser accedidos por medio de la palabra super diferenciándolos por el número
de parámetros que se envíen.
Polimorfismo (Polymorphism)
El polimorfismo es una característica que permite que un mismo objeto tipo Padre pueda hacer referencia (instancias) tanto
de la Clase Padre como de las Clases Hijas, esto permite llamar a métodos con igual nombre, pero que pertenecen a clases distintas y
en tiempo de ejecución se decide qué método es el que se ejecuta (usando instanceof). Como se utiliza la herencia, los objetos
pueden sobreescribir (@Override) los métodos compartidos, con métodos secundarios específicos.
Nota: Al sobreescribir los métodos en la Clase Hija, su identificador de acceso no puede ser más débil que el de la Clase Padre, es
decir, si en la Clase Padre tiene Protected, en la Clase Hija no puede asignarse un Private. Para determinar de qué tipo es, se utiliza la
palabra instanceof la cual nos devuelve un listado de la herencia completa de dicha clase, de lo más particular (Triangle) hasta lo
más genérico (Object)
Returns:
Para utilizar los métodos específicos (no los compartidos) de las clases hijas, es necesario hacer una conversión de tipos (casting) de
Clase Padre a Clase Hija, con la instrucción.
❌
✓ ((Triangle) shape).methodOfTriangleClass(); //Downcasting explicitly
Triangle variable = new Shape(); //Downcasting implicitly, compile-time error
● Upcasting: (Generalization or Widening) is typecasting from a child object to a parent object. Upcasting can be done
implicitly.
Autoboxing y Unboxing
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object
wrapper classes. Unboxing is converting an object of a wrapper type (Integer) to its corresponding primitive (int) value.
Tipo Char
Se utiliza para almacenar caracteres individuales, está considerado también un tipo numérico, si bien su representación habitual es la
del carácter cuyo código almacena, utiliza 16 bits y se usa la codificación UTF-16 de Unicode.
var contador=10;
Clase Scanner
Dentro del paquete java. util, Scanner es una clase que nos permite obtener la entrada de datos primitivos. Esto quiere decir que
podemos capturar datos del tipo int, double, string y etc.
Operador Ternario
La variable resultado recibirá el valor1 en el caso de que la condición sea true o bien el valor2 en el caso de que la condición sea
false.
resultado = (condicion)?valor1:valor2;
Prioridad de operaciones
Solamente crea una nueva referencia en memoria cuando se solicita explícitamente usando la instrucción new String(" ")
Si se usa la instrucción new String(" ").intern(); entonces el String Pool actúa como lo hace normalmente y devuelve una
referencia si es que dicho texto ya existía.
//DECLARING
StringBuilder builder = new StringBuilder();
StringBuilder builderWithText = new StringBuilder("Hello"); // Initial content
//Operations
builder.append("Hola"); // Agregar al final de la cadena
builder.insert(2, "123"); // Insertar en una posición específica
Clase Object
Es una superclase implícita de todas las demás clases. Todas las demás clases son subclases de Object. Tiene ciertos métodos que
se recomienda implementarse en las clases hijas.
● Método toString()
Cuando definimos en una clase el método toString(), imprimimos ahí todo el contenido de los miembros para ese objeto, y se
puede invocar usando System.out.println(objetoClase.toString()); o simplemente System.out.println(objetoClase);
● Método hashCode()
Al implementarse, devuelve enteros distintos para objetos distintos por medio de un cálculo. Se recomienda implementar cuando se
vayan a usar Hashmap, HashSet, HashMap, Hashtable, etc. para facilitar la búsqueda. Devuelve enteros distintos para objetos
distintos.
● Método equals()
Compara el objeto dado con el objeto "this" (el objeto sobre el que se llama el método). Da una forma genérica de comparar objetos
para la igualdad. Se recomienda anular el método equals(Object obj) para obtener nuestra propia condición de igualdad en Objects.
NOTA: En general, es necesario anular el método hashCode() siempre que se anule este método, a fin de mantener el
contrato general para el método hashCode, que establece que los objetos iguales deben tener códigos hash iguales.
En caso de que la función lleve más de un parámetro, el de longitud variable debe ir al final del listado, si no, marca error.
Regular Expressions
A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this
search pattern to describe what you are searching for and can be used to perform all types of text search and text replace operations.
We need to import the java.util.regex The package includes the following classes:
● Pattern Class - Defines a pattern (to be used in a search)
● Matcher Class - Used to search for the pattern
● PatternSyntaxException Class - Indicates syntax error in a regular expression pattern
if(matcher.find()){ //VALIDATE if expression is found in text (it returns the first coincidence)
matcher.group(1); //RETURNS the matching content of the first capturing group
}
while(matcher.find()){ //Use WHILE when multiple coincidences are expected e.g "Game 1: Game 2: Game 3:"
matcher.group(1); //RETURNS the matching content of the first capturing group
}
NOTE: matcher.group(); //When there are not capture groups (expression between parenthesis)
enum Color{
ROJO, VERDE, AZUL;
}
switch(color){
case ROJO: //rojo
case VERDE: // verde
case AZUL: // azul
}
}
En las sentencias case, los nombres de las constantes de enumeración se usan sin estar calificados por el nombre de tipo de
enumeración. Es decir, se utiliza color, no Color.color. Esto se debe a que el tipo de enumeración en la expresión de switch ya ha
especificado implícitamente el tipo de enumeración de las constantes de case.
Por lo tanto, una enumeración puede definir constructores, agregar métodos y tener variables de instancia.
enum Color
{
ROJO(750, 400),
VERDE(525, 526),
AZUL(470, 631);
//Getters
public int getLongitudOnda() {
return this.longitudOnda;
}
public int getFrecuencia() {
return this.frecuencia;
}
}
Bloques de inicialización
● Statick block: De contexto estático: son bloques de código que se ejecutan cuando una clase es cargada, no cuando es
instanciada. Se ejecuta una sola vez.
public class HolaMundo { Output:
public HolaMundo() { 1. Bloque de inicializacion estático
System.out.println("4. Constructor"); 2. Inicio
} 3. Bloque de inicializacion dinámico
4. Constructor
//Bloque de inicialización dinámico 5. Fin
{
System.out.println("3. Bloque de inicializacion dinámico");
}
● Dynamic block: De contexto Dinámico: son bloques de código que se ejecutan cuando una clase es instanciada, pero se
ejecutan justo antes que el constructor. Se ejecuta cada que se instancia la clase.
Memoria en Java
● Memoria Stack: es donde se almacenan las variables locales, se guarda la referencia del objeto.
p1 = 0x333
● Memoria Heap: es donde se almacenan los objetos a los que apuntan las variables locales.
0x333 = tipo Object
https://www.w3resource.com/java-exercises/array/index.php
https://www.youtube.com/watch?v=dGY1e_ebn4w
//SORTING an int[]
Arrays.sort(numeros);
//COPY an array
//with new length (filled with 0 or truncated to that size)
int[] numeros = Arrays.copyOf(numeros1,4);
//FROM this start TO this end
int[] numeros = Arrays.copyOfRange(numeros1,4,5);
//BASIC OPERATIONS
Arrays.toString(arr1); //Returns "[1,3,5,2]" instead of [I@29453f44
Arrays.equals(arr1,arr2); //Check if two int[] arrays are equals
Arrays.binarySearch(arr1,3);//Returns the position where the specified value is found
Arrays.stream(numeros).sum());//Return the sum of all elements in the array
Arrays.stream(numeros).max().orElse(0); //Returns max or 0 if array is empty
Arrays.stream(numeros).filter(e -> e != numRemoved).toArray() //Returns a new array without a num
★ Two dimensional (2-D): array of array in which elements are stored in rows and columns. [How many 1-D
arrays][How many elements per array] ó [row][col]
int[][] twoDim1 = new int[4][5]; /
/Non-rectangular, five integers each row
String[][] letters = { {"a", "b", "c"}, //[0]
{"a", "b", "c"}, //[1]
{"a", "b", "c"} };//[2]
//BASIC OPERATIONS
arrayList.add("text"); //add elements
arrayList.get(0); //returns object at "0" position
arrayList.remove("text"); //remove elements
arrayList.removeIf(x -> x.equalsIgnoreCase("text"));//remove coincidences
//SORTING
missingNumbers.sort(Integer::compareTo);
//or…
numList.sort((x,y) -> x.compareTo(y));
//or…
arrayList.forEach(e ->System.out.println(e));
//or…
arrayList.stream().forEach(e ->System.out.println(e));
★ LinkedList → List
■ Lista enlazada (Consiste en nodos donde cada uno contiene un dato a guardar y una referencia al siguiente nodo de la
lista)
■ Existen Single, double, circular and double circular linked list.
■ Rápido para insertar o remover elementos, lento para obtener.
linkedList.add(1);
linkedList.get(0);
linkedList.remove("d");
■ Hecho a mano:
// A simple Java program for traversal of a linked list
class LinkedList {
Node head; // head of list
llist.printList();
}
}
✓ Vector → List
■ Es igual que ArrayList, pero con la diferencia de que es sincronizada, es decir, se usa con hilos.
✓ Stack → Vector
■ Is a Last-in, First-out. (LIFO) data structure in which only the top element can be accessed. The data is added by push
and removed by pop on top.
■ Es sincronizado.
● Set → Collections
✓ No admite elementos duplicados.
✓ No son sincronizadas (a menos que se adapte con Collections.synchronizedSet)
✓ Dos instancias son iguales si contienen los mismos elementos.
★ Hashset: → Set
■ Almacena los elementos en tablas Hash.
■ No almacena por orden de inserción. Acepta elementos NULL.
■ Buen rendimiento.
★ LinkedHashSet → Set
■ Usa un double link para almacenar el orden de inserción.
■ Set linkedHashSet = new LinkedHashSet(10);
★ SortedSet:→ Set
■ Es una interfaz que tiene métodos extras para mantener el orden de los elementos.
★ TreeSet:→ SortedSet
■ Ordena los elementos.
■ Más lento que HashSet.
■ Los elementos deben implementar la interfaz Comparable.
■ Usa una estructura de árbol para almacenar los elementos.
■ Set treeSet = new TreeSet();
● Map
✓ Asocia key-value.
✓ No contiene claves duplicadas.
✓ No son sincronizadas (a menos que se adapte con Collections.synchronizedMap)
★ HashMap:
■ Sin orden por qué?
■ Buen rendimiento
■ Tamaño inicial por default de 16, por rendimiento se recomienda definir el tamaño inicial.
★ TreeMap:
■ Sorted elements, Ordena las claves en función de su valor.
■ Más lento que HashMap.
■ Las claves deben implementar Comparable.
★ LinkedHashMap
● Queue → Collections
✓ Is a First-in, First-out. (FIFO) data structure. In this structure, new elements are inserted at one end and existing elements are
removed from the other end.
✓ No son sincronizadas
✓ Más usadas con PriorityQueue y LinkedList
Queue<Integer> q = new LinkedList<>();
q.add(1);
int removedele = q.remove(); // To remove the head of queue.
int head = q.peek(); // To view the head of queue
★ PriorityQueue: → Queue
■ each element having a priority associated with it.
Map<Integer, String> linkedHashMap = new LinkedHashMap<Integer, String>();
Queue<String> pq = new PriorityQueue<>();
pq.offer(1); //inserts and attends immediately
pq.poll(); // To remove the head of queue.
Trees
✓ Data structure conformed by: Root, child and leaf (no more children).
★ Binary Tree:
■ Conformed by 0 to 2 child nodes (left & right).
■ Shape:
● Balanced: the height of the left and right subtree of any node differ by not more than 1.
● Unbalanced: the height of the left and right subtree of any node differ by more than 1.
■ Traversal:
● Inorder: 1) Left 2) Root 3) Right
● Preorder: 1) Root 2) Left 3) Right
● Postorder: 1) Left 2) Right 3) Root
Graphs
✓ A graph contains a set of nodes and edges. The nodes are also called vertices. Edges are used to connect nodes. Nodes are
used to store and retrieve data.
The type parameter section, delimited by angle brackets (< >), follows the class name. It specifies the type parameters (also called
type variables) T1, T2, ..., and Tn.
To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public
class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.
All occurrences of Object are replaced by T. A type variable can be any non-primitive type you specify: any class type, any interface
type, any array type, or even another type variable.
Esto puede ser usado en todos los elementos de la interfaz Collection, para que el compilador agregue validaciones en tiempo de
compilación por ejemplo:
Excepciones en Java
Una excepción es un evento que se produce cuando se ejecuta el programa de forma que interrumpe el flujo normal de
instrucciones.Throwable error son los errores en tiempo de ejecución producidos dentro de la JVM y no en nuestros programas, tales
como el OutOfMemoryError.
Leer archivo
File file = new File("fileName.txt");
try {
BufferedReader input = new BufferedReader(new FileReader(file));
String reader = input.readLine();
while(reader != null){ //Reads while there's content in file
System.out.println(reader);
reader = input.readLine();
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace(System.out);
} catch (IOException e) {
e.printStackTrace(System.out);
}
Try-with-resource
Es un bloque try que declara uno o más recursos (objeto que debe ser cerrado después de que el programa terminó con él, ya sea de
forma exitosa o abrupta) asegurándose que todos los recursos son cerrados al final de cada sentencia. Cualquier objeto que
implemente java.lang.AutoCloseable, puede ser usado como un recurso.
static String readFirstLineFromFile(String path) throws IOException {
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
return br.readLine();
}
}
// FileReader y BufferedReader deben ser cerrados, antes se colocaba el cierre dentro del
bloque finally, pero con esto ya no es necesario.
Funciones Lambda
Son funciones anónimas que no necesitan una clase, su estructura es: (parámetros) -> {cuerpo lambda}
Trabajan en conjunto con las interfaces funcionales, para asignar diferentes comportamientos a un método abstracto.
@FunctionalInterface
public interface ICalculadoraLambda {
public int operacion (int x,int y);
}
System.out.println(strategy.sayHelloTo("Oscar Blancarte"));
System.out.println(strategy.sayHelloWord());
}
}
Cuando una expresión lambda es asignada a una interfaz, esta siempre implementará el método abstracto, es por esta razón por la
que solo puede existir un método abstracto y varios defaults.
@FunctionalInterface
public interface Consumer<T> {
//Performs this operation on the given argument
void accept(T t);
}
Consumer //Consumer<INPUT>
Consumer<Integer> display = a -> System.out.println(a);
display.accept(10);
★ Predicate y BiPredicate: Predicate aceptan un solo valor y devuelven un valor booleano mientras que las BiPredicate aceptan
2 parámetros. They both use the test() method.
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
Predicate //Predicate<INPUT>
Predicate<Integer> isAdult = age -> age>18;
System.out.println(isAdult.test(20));
★ Function y BiFunction: Function expressions accept one argument and return one value as a result, whereas BiFunction
expressions accept two arguments and return one result. They both use the apply() method.
@FunctionalInterface
public interface Function<T, R> {//Applies this function to the given argument
// R = return value, t = input argument
R apply(T t);
}
//Example:
List<String> songTitles = Arrays. asList("humble", "element", "dna");
Function<String, String> capitalize = str -> str.toUpperCase() ;
songTitles.stream().map(capitalize).forEach(System.out::println);
//Example:
★ UnaryOperator y BinaryOperator: UnaryOperator recibe un argumento y devuelve un valor del mismo tipo. En las
BinaryOperator se reciben dos argumentos del mismo tipo y devuelve un valor del mismo tipo. Extiende de Function
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T,T>{
//Example:
List<String> dates = new ArrayList<String>();
UnaryOperator<String> replaceSlashes = date -> date. replace("/", "-");
dates.replaceAll(replaceSlashes); //Podría ser también con Function<String,
String> pero el método replaceAll de List solicita que sea UnaryOperator
Con las referencias a los métodos se ofrece una anotación más rápida para expresiones lambda simples y existen 3 tipos diferentes:
★ Métodos estáticos
(Student student, int index) -> student.getRegistry(index) //Expresión lambda sin referencias.
Student::getRegistry //Expresión lambda con referencia a método de un tipo.
Arrays.sort(nombres, String::compareToIgnoreCase);
● Stream API
✓ Se agrega el método por default stream() en la clase Collection.
✓ Con parallelStream()se ejecutan operaciones en paralelo (multi-threading).
✓ Realiza operaciones funcionales sobre cualquier objeto de tipo Collection sin modificar el objeto original, sino que entrega
un tipo Stream.
✓ Sustituye iteraciones, como for, for-each, while.
✓ Permite operaciones encadenadas.
✓ Se dividen en intermediate operations (Stream<T> ) y terminal operations (regresa un resultado de un tipo definido).
✓ Filter: devuelve un nuevo Stream con solo los elementos que satisfacen el Predicate.
Stream<String> stream = list.stream().filter(element -> element.contains("d"));
✓ map(): convierten elementos de un Stream, aplicando una función a cada uno de los elementos de la colección, agregándolos
a un nuevo Stream.
numberList.stream().map(x -> Integer.valueOf(x) + 2)
//Returns a new Stream with all elements + 2
✓ reduce(): reduce una secuencia de elementos de acuerdo a una función y los acumula al valor inicial especificado.
List<Integer> list = Arrays.asList(1, 1, 1);
Integer reduced = list.stream().reduce(23, (a, b) -> a + b);
//sums 23 + [the list] = 26
✓ collect(): reduce un Stream en un Collection o un Map. Puede usar toList(), toMap(), toSet()
List<String> resultList = numberList.stream().map(element ->
element.toUpperCase()).collect(Collectors.toList());//reduce el Stream a un
List
List names =
people.stream().map(Person::getName).collect(Collectors.toList()); //A partir
de una lista de personas, obtenemos una lista con todos los nombres.
✓ Collectors.summarizingDouble(): regresa un objeto DobleSummaryStatistics con estadísticas como conteo, suma, mínimo,
máximo, promedio, etc.
DobleSummaryStatistics statistics = products.stream()
.collect(Collectors.summarizingDouble(Product::getPrice));
✓ Stream builder: This allows the creation of a Stream by generating elements individually and adding them to the Builder
Stream<String> stream = Stream.<String>builder().add("a").add("b").build();
stream.forEach(System.out::println);
Java 9
✓ dropWhile() permiten descartar o tomar elementos del stream mientras se comprueba una condición.
✓ TakeWhile()
✓ ofNullable(): devuelve un stream de un elemento o vacío dependiendo de si el objeto es null o no.
✓ iterate(): permiten generar un secuencia de valores similar a un bucle for.
● Marker interface
A marker interface is an interface that doesn’t have any methods or constants inside it. It provides run-time type information about
objects, so the compiler and JVM have additional information about the object.Is also called a tagging interface.
Though marker interfaces are still in use, they very likely point to a code smell, and we should use them carefully. The main reason for
this is that they blur the lines of what an interface represents, since markers don’t define any behavior. Newer development favors
annotations to solve some of the same problems.
https://www.baeldung.com/java-8-streams#:~:text=Java%208%20offers%20the%20possibility,%3A%20IntStream%2C%20LongStream
%2C%20DoubleStream
● Java.time
✓ Nueva API para fechas, horas, instantes y duraciones en formato ISO (yyyy-MM-dd).
✓ Incluye LocalDate (2022-08-07), LocalTime (10:36), LocalDateTime (2022-08-07T10:36), ZonedDateTime
(2022-08-07), Period, Duration
✓ Todas las clases son inmutables y Thread-safe.
LocalTime sevenThirty =
LocalTime.parse("06:30").plus(1,ChronoUnit.HOURS);
int sevenThirty = LocalTime.parse("06:30").getHour();
boolean sevenThirty =
LocalTime.parse("06:30").isBefore(LocalTime.parse("07:30"));
LocalTime sevenThirty = LocalTime.MAX //23:59:59.99
★ Period: usado para modificar los vsalores de una fecha u obtener diferencia entre dos fechas. Representa una cantidad de
tiempo en términos de años, meses y días.
LocalDate.parse("2007-05-10").plus(Period.ofDays(5));
int fiveDays = Period.between(initialDate, finalDate).getDays();
long fiveDays = ChronoUnit.DAYS.between(initialDate, finalDate);
https://www.baeldung.com/java-8-date-time-intro
● Optional
✓ Objeto contenedor que puede o no contener un valor null.
✓ ofNullable() regresa Optional[valor] o Optional.empty
✓ isPresent() regresa true o false
✓ ifPresent() ejecuta un bloque si el valor es presente.
✓ get() regresa el valor, si está presente, si es null regresa NoSuchElementException
✓ orElse() si es null, regresa un valor por defecto
✓ orElseGet() regresa el valor si está presente, si es null, regresa el valor generado por un Supplier
✓ orElseThrow() regresa el valor si está presente, si es null, regresa la excepción generada por un Supplier
✓ of() regresa un Optional con el valor especificado
✓ empty() regresa un Optional.empty
✓ map regresa un Optional con el resultado de aplicar una función mapping, si es null, regresa Optional.empty
Java 9
Optional<Integer> op = Optional.empty();
op.or(() -> Optional.of(100)) //returns Optional[100]
● Métodos de copia
Se incluye el método estático copyOf() en interfaces de Collection para crear copias inmutables.
● Métodos de reducción
La clase Collectors incluye otros 3 métodos además de toList(), toSet() y toMap() de Java 8 para reducir un Stream a
Collection. Dichos métodos son: método estático toUnmodificableSet(), toUnmodificableList(), toUnmodificableMap(),
para generar colecciones inmutables.
✓ repeat(n) retorna un String cuyo valor es la concatenación de el String dado, repetido n veces.
String str = "Abc";
System.out.println(str.repeat(3));//AbcAbcAbc
✓ Strip() retorna un String dado con todos los espacios al inicio y final removidos. Puede ser también StripLeading() o
StripTrailing().
String str = "Abc";
System.out.println(str.repeat(3));//AbcAbcAbc
● Comparación en StringBuilder
Es posible comparar dos StringBuilder lexicográficamente sin necesidad de transformarlos en String, ya que la clase dispone del
método compareTo.
sb1.CompareTo(sb2);
//-1: sb1 < sb2
// 0: sb2 = sb1
// 1: sb1 > sb2
Novedades Java 12