28 Aralık 2020 Pazartesi

Jakarta EE

Giriş
Jakarta 9 ile javax.* isim alanı jakarta.* olarak değiştirildi. Çünkü Java Community Process (JCP)'den Eclipse Foundation' a devredildi

Jakarta EE aslında sadece bir specification. Bunu gerçekleştirenler GlassFish, JBoss, WebSphere gibi Application Server'lar.

Javadoc burada.

Arayüzler
TimerService Arayüzü

Anotasyonlar
@Model Anotasyonu
Açıklaması şöyle
The CDI framework provides us with a built-in stereotype @javax.enterprise.inject.Model which is intended for use with beans that define the model layer of an MVC web application architecture such as Jakarta Server Faces.

Widfly
Widfly yazısına taşıdım

25 Aralık 2020 Cuma

Java 13 Text Blocks

Giriş
Java 13 ile geliyor. Çok satırlı (multi-line) string imkanı tanıyor. Text Block """ ile başlar ve """ ile biter. Açıklaması şöyle
The opening delimiter is defined by a sequence of three double quotes, followed by zero or more spaces and a line terminator. The content of the text block starts from the first character after the line terminator. Therefore, any white spaces between the three quotation marks and the line terminator are not taken into consideration.

The closing delimiter, on the other hand, is defined only by three double quotes sequence. The content of the text block ends with the character preceding the first double quotes in the sequence, of the closing delimiter.
Derleme Aşamaları
Açıklaması şöyle
There are three phases that are performed during compile-time:

- Normalization of line terminators.
- Removal of white spaces that were introduced to align the text block with the Java code.
- Interpretation of escape characters.
1. Normalization of Line Terminators
Açıklaması şöyle. Yani Line Terminator olarak \n karakteri kullanılır
Normalization for text blocks always transforms all line terminators into LF, regardless of the platform on which it runs. 
2. Removing Superfluous White Spaces
Açıklaması şöyle
After the normalization process, a text block will clearly consist of one or more lines. The algorithm for removing superfluous white spaces, (i.e., the spaces introduced to align the text block code with the Java code) includes:

- The removal of all of the white spaces that are at the end of each line.
- The removal of all of the white spaces that are at the beginning of each line, common to all lines.
Açıklaması şöyle
The algorithm described in this section is implemented through the use of the static method of the String class introduced with Java 13 stripIndent.
Örnek
Şöyle yaparız. Burada en son kapanma bölümünü satır başına aldığımı için "minimum number of common initial white spaces" 0 oluyor, çıktı da sağa doğru kayar
String textBlock = """
    This is a text block!
""";
3. Interpretation of escape characters
Açıklaması şöyle. Yani \" yapmaya gerek yok
Technically it is also possible to use the escape characters, and \", but it is useless and therefore not recommended.


Optional.orElse metodu - Sabit Değer Döner

Giriş
Optional.orElse() daha çok metod sonucunda null dönme ihtimali varsa null dönmek yerine default bir değer dönmek için kullanılır. Açıklaması şöyle. yapılır.
Returns the value if present otherwise, returns other.
İmzası şöyle
public T orElse(T other)
//If a value is present, returns the value, otherwise returns other.
//Parameters:
//other - the value to be returned, if no value is present. May be null.
//Returns:
//the value, if present, otherwise other

İlgili Metodlar
orElse ile ilgili diğer metodlar şöyle
isPresentOrElse() 

orElseGet() ile Farkı
orElseGet() lazy çalışır. orElse() ise lazy değildir

Elimizde şöyle bir kod olsun.  orElse() kullandığımız için myFunc() metodunun çağrıldığını görürüz.
Optional<Foo> opt = ...
opt.orElse(myFunc(...));
orElseGet() lamda aldığı için lazy. Dolayısıyla çözüm olarak şöyle yapmak gerekir.
opt.orElseGet(() -> myFunc(...));
Yanlış Kullanım
Örnek - orElse(null)
Varsayılan değer olarak null dönmek çok iyi bir fikir değil.

Doğru Kullanım
Örnek
Elimizde şöyle bir kod olsun
public String getPersonName() {
  Optional<String> name = getName();
  if (name.isPresent()) {
    return name.get();
  }
  return "DefaultName";
}
Bu kodu şöyle yapabilirim
public String getPersonName() {
  Optional<String> name = getName();
  return name.orElse("DefautName");
}

23 Aralık 2020 Çarşamba

Collectors.maxBy metodu

Örnek
Şöyle yaparız
List<String> strings = Arrays.asList("alpha","beta","gamma");
strings .stream() .collect(Collectors.maxBy(Comparator.naturalOrder())) .get(); // output: gamma

Collectors.minBy metodu

Örnek
Şöyle yaparız
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
List<String> strings = Arrays.asList("alpha","beta","gamma");
integers
    .stream()
    .collect(Collectors.minBy(Comparator.naturalOrder()))
    .get();
// output: 1
strings
   .stream()
   .collect(Collectors.minBy(Comparator.naturalOrder()))
   .get();
// output: alpha

Collectors.counting metodu

Giriş 
Döndürülen collection içindeki eleman sayısını verir

Stream.count() vs Collectors.counting()
Aslında her ikisi de aynı şeyi yapıyorlar. 

Fark 1
Yani şu ikisi de aynı çıktıyı verir
System.out.println(Stream.of(1, 2, 3, 4, 5)
        .map(i -> {
            System.out.println("processing " + i);
            return i * 2;
        }).count());

System.out.println(Stream.of(1, 2, 3, 4, 5)
        .map(i -> {
            System.out.println("processing " + i);
            return i * 2;
        }).collect(Collectors.counting()));
Ama Stream.count() gerekirse, aradaki işlemleri atlayarak direkt sonuç dönebilir. Açıklaması şöyle
An implementation may choose to not execute the stream pipeline (either sequentially or in parallel) if it is capable of computing the count directly from the stream source. In such cases no source elements will be traversed and no intermediate operations will be evaluated...
Fark 2
Collectors.counting() aslında gruplama için daha uygun. Şöyle yaparız
Map<String, Long> collect = 
   wordsList.stream().collect(groupingBy(Function.identity(), counting())); 
Kullanım

Örnek
Şöyle yaparız
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
Long collect = integers
                   .stream()
                   .filter(x -> x < 4)
                   .collect(Collectors.counting());
// output: 3
Örnek
Elimizde bir sözcük listesi olsun. Listedeki sözcüklerin frekans tablosunu çıkarıp belli bir değerin üzerinde olan sözcüklerin sayısını şöyle buluruz.
int countThreshold = 2;
long sum =
    words.stream()
          .collect(Collectors.groupingBy(Function.identity(),
                                         Collectors.counting()))
          .values()
          .stream()
          .filter(x -> x >= countThreshold)
          .reduce(0L, Long::sum);
Örnek
İki setin kesişimi kaç tane elemandan oluşur diye bulmak isteyelim. Şöyle yaparız.
Set<String> sOne = ...; Set<String> sTwo = ...;
long numFound = sOne.parallelStream()
                    .filter(segment -> sTwo.contains(segment))
                    .collect(Collectors.counting());


Collectors.toUnmofifiableList metodu

Giriş 
Java 10 ile geliyor. Açıklaması şöyle.
The Collectors.toUnmodifiableList would return a Collector that disallows null values and will throw NullPointerException if it is presented with a null value.
Örnek
Şöyle yaparız.
List<Integer> result = Arrays.asList(1, 2, 3, 4)
            .stream()
            .collect(Collectors.toUnmodifiableList());