11 Şubat 2020 Salı

Tables Sınıfı

Giriş
Şu satırı dahil ederiz.
import com.google.common.collect.Tables;
toTable metodu
Table nesnesinin Java 8 Stream ile kullanılabilmesini sağlar. Bir Collector döner.

Birinci parametre rowFunction, ikinci parametre columnFunction, üçüncü parametre valueFunction, dördünce parametre mergeFunction, beşinci parametre tableSupplier olarak kullanılır.

mergeFunction aynı row ve column değerlerine sahip satırlarda value değerini hesaplamak içindir.

toTable metodu - rowFunction + columFunction + valueFunction + tableSupplier
Örnek
Elimizde şöyle bir kod olsun.
List<ApplicationUsage> appUsageFromDB =
Şöyle yaparız. TableSupplier olarak HashBasedTable::create veriyoruz.
Table<String, String, ApplicationUsage> table2 = appUsageFromDB.stream()
  .collect(Tables.toTable(
    ApplicationUsage::getId,
    ApplicationUsage::getName,
    au -> au,
    HashBasedTable::create
));
Örnek
Elimizde iki tane table olsun.
Table<Long,String,Integer> tableOne
Table<Long,String,Integer> tableTwo
Table 1 şöyle olsun.
1L Fruits     20
2L Fruits     30
2L Vegetables 15
3L Vegetables 10
Table 2 şöyle olsun.
2L Fruits     10
2L Vegetables 40
3L Fruits     15
4L Vegetables 35
Birleşim olan Table 3 şöyle olsun isteyelim.
1L Fruits     20
2L Fruits     30 + 10 = 40
2L Vegetables 15 + 40 = 55
3L Vegetables 10
3L Fruits     15
4L Vegetables 35
Şöyle yaparız.
HashBasedTable<Long, String, Integer> sumTable = Stream.concat(
  tableOne.cellSet().stream(), tableTwo.cellSet().stream())
    .collect(Tables.toTable(Table.Cell::getRowKey,
      Table.Cell::getColumnKey,
      Table.Cell::getValue,
      Integer::sum, HashBasedTable::create));
toTable metodu - rowFunction + columFunction + valueFunction + + mergeFunction + tableSupplier
Örnek
Şöyle yaparız.
Table<Region, Country, List<City>> table = RECORDS.stream()
        .collect(toTable(
                r -> r.getRegion(),
                r -> r.getCountry(),
                r -> Lists.newArrayList(r.getCity()),
                (l, l2) -> {
                    l.addAll(l2);
                    return l;
                },
                HashBasedTable::create
        ));
Örnek
Şöyle yaparız.
Map<Integer, Integer> source = ...;

// compiles
Table<Integer, Integer, Integer> broker = source.entrySet().stream()
  .collect( Tables.toTable( e -> 0, e -> 0, e -> 0,
                    ( e1, e2 ) -> 0, HashBasedTable::create ) );
Örnek
Şöyle yaparız. row değeri owner, column değeri status ve value 1 olur. aynı row ve column değerleri için value toplanır.
List<Thing> listOfThings = ...;

Table<Owner, Status, Long> table = 
  listOfThings.stream().collect(
    Tables.toTable(
      Thing::getOwner,             // Row key extractor
      Thing::getStatus,            // Column key extractor
      thing -> 1,                  // Value converter (a single value counts '1')
      (count1, count2) -> count1 + count2, // Value merger (counts add up)
      HashBasedTable::create       // Table creator
  )
);

10 Şubat 2020 Pazartesi

MoreFiles Sınıfı

Giriş
Şu satırı dahil ederiz.
import com.google.comon.io.MoreFiles;

3 Şubat 2020 Pazartesi

MoreCollectors Sınıfı

onlyElement metodu
Açıklaması şöyle.
With this API, the Collector takes a stream containing just one element and returns the element; if the stream contains more than one element it throws IllegalArgumentException or if the stream contains zero element it throws NoSuchElementException.
Örnek
Şöyle yaparız.
import static com.google.common.collect.MoreCollectors.onlyElement;

User match =
    users.stream().filter((user) -> user.getId() < 0).collect(onlyElement());

31 Ocak 2020 Cuma

LinkedListMultimap Sınıfı

Giriş
ListMultimap arayüzünü gerçekleştirir.

Bu arayüzü gerçekleştiren sınıflar şöyle
ArrayListMultimap, ForwardingListMultimap, ImmutableListMultimap, LinkedListMultimap

Multimap'in sağ tarafı yani value değerlerini tutan tarafı LinkedList'tir.

create metodu
Örnek
Şöyle yaparız.
ListMultimap <String, Double> multimap = LinkedListMultimap.create(); 
Örnek
Şöyle yaparız.
Multimap<Integer, Integer> linkedHashMap = LinkedListMultimap.create();
get metodu
Şöyle yaparız. List döndürdüğü için stream() ile kullanılabilir.
multimap.get(...).stream().mapToDouble(d -> d).sum();
put metodu
Şöyle yaparız.
Multimap<Integer, Integer> linkedHashMap = ...
linkedHashMap3.put(1, 2);

16 Ocak 2020 Perşembe

MinMaxPriorityQueue Sınıfı

Giriş
Guava'da "Circular Ring" olarak tabir edilebilecek iki tane temel veriyapısı var.Bunlar şöyle.
EvictingQueue
MinMaxPriorityQueue

create metodu
Şöyle yaparız.
MinMaxPriorityQueue<CustomClass> queue = MinMaxPriorityQueue
  .orderedBy(Comparator.comparing(CustomClass::getValue))
  .maximumSize(10)
  .create();

7 Ocak 2020 Salı

Maven

Giriş
pom.xml dosyasına eskiden şu satırı dahil ederdik..
 <dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>21.0</version>
 </dependency>    
Daha sonra versio alanı -jre uzantısı ile bitmeye başladı. Yani şu satırı dahil ederiz. Ben 27.1-jre sürümünü kullandım
<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>25.0-jre</version>
</dependency>

1 Ocak 2020 Çarşamba

MoreExecutors Sınıfı

Giriş
Şu satırı dahil ederiz.
import com.google.common.util.concurrent.MoreExecutors;
directExecutor metodu
Açıklaması şöyle.
This is a lightweight executor that can run tasks on the thread that calls the execute method.
Metodun içi şöyle.
public static Executor directExecutor() {
  return DirectExecutor.INSTANCE;
}
getExitingExecutorService metodu
Açıklaması şöyle.
...converts a given ThreadPoolExecutor to an ExecutorService that exits when the application is complete. It will tweak the ThreadPoolExecutor to make it produce daemon threads. And it will register a ShutdownHook to wait for their completion. That’s something you don’t want to write yourself even if it’s not complicated. It’s useful if you want your application to end gracefully even if some ExecutorService was created somewhere.
Örnek
Şöyle yaparız.
ExecutorService exec = MoreExecutors.getExitingExecutorService(
  (ThreadPoolExecutor) Executors.newFixedThreadPool(4), 
  100_000, TimeUnit.DAYS//period after which executor will be automatically closed
                        //I assume that 100_000 days is enough to simulate infinity
);
listeningDecorator metodu
Açıklaması şöyle.  ListeningExecutorService veya ListeningScheduledExecutorService nesnesi döner. ListeningExecutorService sayesinde ListenableFuture nesnesi elde ederiz.
Listening decorators allow you to wrap the ExecutorService and receive ListenableFuture instances upon task submission instead of simple Future instances. The ListenableFuture interface extends Future and has a single additional method addListener. This method allows adding a listener that is called upon future completion.
Örnek
Şöyle yaparız.
ListeningScheduledExecutorService scheduledExecutorService = MoreExecutors
                .listeningDecorator(Executors.newScheduledThreadPool(20));
Örnek
Şöyle yaparız.
ListenableFuture<T> future = MoreExecutors.listeningDecorator(executor).submit(()->{
  ...
});
newDirectExecutorService metodu
Açıklaması şöyle.
This method returns an instance of ListeningExecutorService. It is a heavier implementation of Executor that has many useful methods. It is similar to the deprecated sameThreadExecutor() method from previous versions of Guava.
shutdownAndAwaitTerminaton metodu
1. shutdown() metodunu çağırır. Başlamış olan işler devam eder ancak ExecutorService yeni iş kabul etmez.
2. awaitTermination() metodunu çağırır. Devam etmekte olan işlerin bitmesini bekler.
3. shutdownNow() metodunu çağırır. Zorla thread'leri durdurur
4. awaitTermination() metodunu bir kere daha çağırır. Devam etmekte olan işlerin bitmesini bekler.

Örnek
Şöyle yaparız.
ExecutorService executor = ...;
MoreExecutors.shutdownAndAwaitTermination(executor, 60, TimeUnit.SECONDS);