10 Ağustos 2023 Perşembe

Arrays.asList metodu

Giriş
İmzası şöyle.
List<T> asList (T...a);
Açıklaması şöyle
When we do Arrays.asList(array) it creates a fixed-size list backed by the specified array. We can’t modify it’s length thus adding or removing is not allowed. And also it is not copied or created, it is just view of the same array, so if you update the value of an element in the list it will also change the element in the original array.
Metod Arrays$ArrayList nesnesi döner. Bu metod Java 9 ile gelen List.of() metodu ile karşılaştırılabilir.

Örnek
Bellek alanı olarak belirtilen array'i kullanan read only bir liste döner.  Açıklaması şöyle
Returns a fixed-size list backed by the specified array.
Şöyle yaparız.
List<Integer> list = Arrays.asList(new Integer[desiredLength]);
Eğer array değişirse liste de değişir. Şöyle yaparız.
Integer[] array = {1,2,3};
List<Integer> list = Arrays.asList(array);
array[1] = 10;
System.out.println(list); // Prints [1, 10, 3]
Örnek - null eleman
null eleman olabilir. Şöyle yaparız.
List<Integer> list = Arrays.asList(1, 2, null); // OK
Dolayısıyla null araması yapılabilir. Şöyle yaparız.
List<Integer> list = Arrays.asList(1, 2, 3);
list.contains(null); // Return false
Örnek - farklı tipler
Şöyle yaparız.
List list1 = Arrays.asList(1L, 2.0F, "3");
var list2 = list1;
Örnek - farklı tipler
Elimizde şöyle bir kod olsun. Çıktı olarak Object[] alırız çünkü int[] ve String[]'in ortak tek atası Object[]'dir
System.out.println(Arrays.asList(false? new int []{2} :new String[]{"2"}));
Örnek - ekleme çıkarma
Bu listeye ekleme çıkarma işlemi yapılamaz yoksa UnsupportedExcetion fırlatılır. Elimizde altta Array kullanan bir liste olsun.
String[] arr = {"a", "b"};
List<String> list = Arrays.asList(array);
Bu listeye ekleme yaparsak exception fırlatılır. Şöyle yaparız.
try {
  list.add("c");
}
catch(UnsupportedOperationException e) {
  // Fixed-size
}
Eğer Arrays.asList()'in sonucuna da bir şey eklemek istersek şöyle yaparız.
List<Foo> list= new ArrayList<>(Arrays.asList(...));
Örnek - değiştirme
Liste'deki eleman değiştirilebilir. Şöyle yaparız.
List<Integer> list = Arrays.asList(1, 2, null);
list.set(1, 10); // OK
Örnek - array
Açıklaması şöyle
Arrays.asList(int[]) - will create a List<int[]>
Eğer T Object'ten kalıtan bir tipse, çoklu elemana sahip bir liste dönüyor. Eğer T primitive ise tek elemana sahip bir liste döner. Aşağıdaki kod bize List<char> değil, tek elemanı sahip List<char[]> döner.
char[] alpha = {...};
Arrays.asList(alpha)
Çözüm
Primitive tipleri nesne olarak geçeriz. Şöyle yaparız.
Integer[] array = {3, 2, 5, 4};

if (Arrays.asList(array).contains(3))
{
  System.out.println("The array contains 3");
}
Çözüm
asList yerine "double curly brace initialization" kullanılabilir. Şöyle yaparız.
List<String> list = new ArrayList<String>() {{
  add("one");
  add("two");
  add("three");
}};
Çözüm
Listeye çevirmek yerine direkt stream'e çeviririz. Şöyle yaparız.
Arrays.stream(array)

AWS S3 API AmazonS3 Kullanımı

Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk</artifactId>
  <version>1.12.83</version>
</dependency>
Daha sonra
AmazonS3 Sınıfı ile senkron istemci yaratılır

Eski kodlarda S3AsyncClient  Sınıfı ile asenkron istemci yaratılır

8 Ağustos 2023 Salı

JEP 359 record ve Serialization

Örnek
Şöyle yaparız
record Range(int low, int high) implements Serializable {
private Object readResolve() { if (high < low) { throw new IllegalStateException("Serialized object has high value less than low value"); } return this; } }

4 Ağustos 2023 Cuma

JEP 430 - java.lang.StringTemplate.Processor Arayüzü - JDK 21 İle Geliyor Custom Template Processor İçindir

Giriş
Açıklaması şöyle
Template processing is built upon the newly added nested functional interface java.lang.StringTemplate.Processor:
How the processing works is that the String literal containing the expression is converted to a StringTemplate and given to a Processor.

If we want to create a JSONObject, we need to interpolate the String literal first, and then create the new instance of the desired return type. Using the static helper Processor.of makes this quite easy:
@FunctionalInterface
public interface Processor<R, E extends Throwable> {

  R process(StringTemplate stringTemplate) throws E;

  static <T> Processor<T, RuntimeException> of(
    Function<? super StringTemplate, ? extends T> process) {
    return process::apply;
  }

  // ...
}
of metodu
Örnek
Açıklaması şöyle
How the processing works is that the String literal containing the expression is converted to a StringTemplate and given to a Processor.

If we want to create a JSONObject, we need to interpolate the String literal first, and then create the new instance of the desired return type. Using the static helper Processor.of makes this quite easy:
Şöyle yaparız Önce bir Processor yaratıyoruz. Sonra StringTemplate nesnesi Processor'a geçiliyor.
/// CREATE NEW TEMPLATE PROCESSOR
var JSON = StringTemplate.Processor.of(
  (StringTemplate template) -> new JSONObject(template.interpolate())
);

// USE IT LIKE BEFORE
JSONObject json = JSON."""
{
  "user": "\{
    // We only want to use the firstname
    this.user.firstname()
  }",
  "temperatureCelsius: \{tempC}
}
""";
StringTemplate.Processor<JSONObject, JSONException> JSON = template -> {
  String quote = "\"";
  List<Object> newValues = new ArrayList<>();

  for (Object value : template.values()) {
    if (value instanceof String str) {
      // SANITIZE STRINGS
      // the many backslashes look weird, but it's the correct regex
      str = str.replaceAll(quote, "\\\\\"");
      newValues.add(quote + str + quote);
    }
    else if (value instanceof Number || value instanceof Boolean) {
      newValues.add(value);
    }
    // TODO: support more types
    else {
      throw new JSONException("Invalid value type");
    }
  }

  var json = StringTemplate.interpolate(template.fragments(), newValues);

  return new JSONObject(json);
};