ARTICLE AD BOX
1. STRUCTURA CLASE (OOP)
public enum TipEnum { VAL1, VAL2, VAL3 }
public class ClasaBaza {
private String nume;
private int valoare;
private TipEnum tip;
public ClasaBaza() {} // OBLIGATORIU pentru Jackson JSON
public ClasaBaza(String nume, int valoare, TipEnum tip) {
this.nume = nume; this.valoare = valoare; this.tip = tip;
}
public String getNume() { return nume; }
public void setNume(String nume) { this.nume = nume; }
public int getValoare() { return valoare; }
public void setValoare(int valoare) { this.valoare = valoare; }
public TipEnum getTip() { return tip; }
public void setTip(TipEnum tip) { this.tip = tip; }
@Override
public String toString() {
return "ClasaBaza{nume=" + nume + ", valoare=" + valoare + "}";
}
}
public class ClasaDerivata extends ClasaBaza {
private int atribut;
public ClasaDerivata() {}
public ClasaDerivata(String nume, int valoare, TipEnum tip, int atribut) {
super(nume, valoare, tip);
this.atribut = atribut;
}
public int getAtribut() { return atribut; }
public void setAtribut(int atribut) { this.atribut = atribut; }
@Override
public String toString() {
return super.toString() + " atribut=" + atribut + "}";
}
}
2. COLECTII
// SET
Set<ClasaBaza> colectie = new HashSet<>();
colectie.add(new ClasaDerivata(...));
colectie.forEach(System.out::println);
// LIST
List<ClasaBaza> lista = new ArrayList<>();
lista.add(new ClasaDerivata(...));
ClasaBaza ultimul = lista.get(lista.size() - 1);
ClasaBaza primul = lista.get(0);
3. CITIRE FISIER TEXT (BufferedReader)
import java.io.*;
public static List<ClasaBaza> citireText() throws IOException {
List<ClasaBaza> lista = new ArrayList<>();
BufferedReader br = new BufferedReader(
new FileReader("src/main/resources/date.txt"));
String linie;
while ((linie = br.readLine()) != null) {
String[] p = linie.split(",");
if (p[0].trim().equals("Derivata1")) {
lista.add(new ClasaDerivata1(p[1], Integer.parseInt(p[2]),
TipEnum.valueOf(p[3]), Integer.parseInt(p[4])));
} else {
lista.add(new ClasaDerivata2(p[1], Integer.parseInt(p[2]),
TipEnum.valueOf(p[3]), p[4]));
}
}
br.close();
return lista;
}
// Conversii utile:
// Integer.parseInt(p[1]) String -> int
// Boolean.parseBoolean(p[2]) String -> boolean
// TipEnum.valueOf(p[3]) String -> Enum
// LocalDate.parse(p[4]) String -> LocalDate (format: yyyy-MM-dd)
4. CITIRE/SCRIERE JSON (Jackson) -- pom.xml necesar!
<!-- pom.xml -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.14.2</version>
</dependency>
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
// Daca ai mostenire (2 tipuri in colectie) -- foloseste Wrapper:
public class Wrapper {
private List<ClasaDerivata1> lista1;
private List<ClasaDerivata2> lista2;
public Wrapper() {}
// getteri + setteri
}
// SCRIERE
public static void scriere(Wrapper w) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.writeValue(new File("src/main/resources/date.json"), w);
} catch (IOException e) { e.printStackTrace(); }
}
// CITIRE -- tip simplu (un singur tip de obiect)
public static List<ClasaBaza> citire() {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
return mapper.readValue(new File("src/main/resources/date.json"),
new TypeReference<List<ClasaBaza>>(){});
} catch (IOException e) { e.printStackTrace(); }
return null;
}
// CITIRE -- cu Wrapper (doua tipuri)
public static Wrapper citire() {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
return mapper.readValue(new File("src/main/resources/date.json"),
Wrapper.class);
} catch (IOException e) { e.printStackTrace(); }
return null;
}
// In main() cu Wrapper:
Wrapper w = citire();
Set<ClasaBaza> colectie = new HashSet<>();
colectie.addAll(w.getLista1());
colectie.addAll(w.getLista2());
---
## 5. CITIRE TASTATURA CU VALIDARE (try-catch)
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int x = 0;
boolean valid = false;
while (!valid) {
try {
System.out.print("Introduceti x: ");
x = Integer.parseInt(sc.nextLine());
valid = true;
} catch (NumberFormatException e) {
System.out.println("Valoare invalida! Reintroduceti.");
}
}
final int xFinal = x; // necesar pentru lambda
---
## 6. STREAM API -- Operatii esentiale
import java.util.stream.*;
// FILTRARE simpla
colectie.stream()
.filter(t -> t.getValoare() > xFinal)
// FILTRARE dupa tip (instanceof)
colectie.stream()
.filter(t -> t instanceof ClasaDerivata1)
.map(t -> (ClasaDerivata1) t)
.filter(t -> t.getAtribut() > xFinal)
// AFISARE DOAR UN CAMP (map)
colectie.stream()
.map(ClasaBaza::getNume)
// SORTARE crescatoare
colectie.stream()
.sorted(Comparator.comparing(ClasaBaza::getValoare))
// SORTARE descrescatoare
colectie.stream()
.sorted(Comparator.comparing(ClasaBaza::getValoare).reversed())
// PRIMELE N elemente
lista.stream()
.limit(nFinal)
// GASIRE PRIMUL element
ClasaBaza gasit = colectie.stream()
.filter(t -> t.getTip().equals(TipEnum.VAL1))
.findFirst()
.get();
// COLECTARE intr-o lista noua
List<String> rezultat = colectie.stream()
.filter(t -> !t.isEch())
.map(ClasaBaza::getNume)
.collect(Collectors.toList());
// COLECTARE intr-un Set
Set<String> rezultatSet = colectie.stream()
.map(ClasaBaza::getNume)
.collect(Collectors.toSet());
---
## 7. RECORD
public record NumeRecord(ClasaBaza centru, ClasaDerivata curs) {}
// Creare Set de record-uri cu Stream
Set<NumeRecord> setRecord = colectie.stream()
.map(c -> new NumeRecord(c, c.getLista().get(0)))
.collect(Collectors.toSet());
setRecord.forEach(System.out::println);
---
## 8. LOCALDATE
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
LocalDate data = LocalDate.of(2020, 3, 15); // creare
LocalDate acum = LocalDate.now(); // data curenta
long ani = ChronoUnit.YEARS.between(data, acum); // diferenta in ani
int an = data.getYear(); // extrage anul
// Comparare:
data.isAfter(LocalDate.of(2010, 1, 1)) // dupa 2010
data.isBefore(LocalDate.now()) // inainte de acum
data.getYear() > 2010 // alternativ
