Giriş
Şu satırı dahil
ederiz.
import java.util.Collections;
addAll metodu
İkinci diziyi birinci Collection nesnesine ekler. Eğer eklenecek ikinci parametre ise bu metod kullanılır. Eğer eklenecek ikinci parametre Collection ise çoğu veri yapısı zaten addAll() metodu sunuyor.
Örnek
Şöyle
yaparız
Vector<String> v = ...;
String arr [] = ...;
Collections.addAll(v,arr);
Örnek
Şöyle
yaparız
Collections.addAll(queue, array);
binarySearch metodu
Arrays.binarySearch ile aynıdır. Metodun imzası
şöyle.
Collections.binarySearch(List<? extends Comparable<? super T>> list, T key)
Açıklaması
şöyle.
The return value is the same for both forms. If the List contains the search key, its index is returned. If not, the return value is (-(insertion point) - 1), where the insertion point is the point at which the value would be inserted into the List, or the index of the first element greater than the value or list.size() if all elements in the List are less than the specified value.
Örnek
Elimizde 1,3 değerlerini içeren bir liste olsun
//Bulunursa
Aranan 1 : Sonuç 0
Aranan 3 : Sonuç 1
//Bulunamazsa
Aranan 2 : Sonuç -2. Gerçek konum : 1
Aranan 4 : Sonuç -3. Gerçek konum : 2
Aranan 0 : Sonuç -1. Gerçek konum : 0
Yani sonuç >= 0 ise değer bulunmuştur. Eğer <0 ise gerçek konumu bulmak için -(sonuc + 1) yapılır.
Ya da sonuç -1 ise başa eklenecektir. < -1 ise araya veya sona eklenecektir.
disjoint metodu
İki dizinin birbirleriyle kesişimi yoksa, true döner. Aynı şeyi
CollectionUtils.containsAny() metoduyla yapmak mümkün.
Örnek
Şöyle
yaparız.
List<Foo> list1 = ...;
List<Foo> list2;
boolean result = Collections.disjoint(list1, list2);
Örnek
Kesişim olduğunu bulmak için şöyle
yaparız.
return !Collections.disjoint(list1, list2);
Örnek
Aslında dizilerin sıralı olduğunu biliyorsak şöyle
yapabiliriz.
public static final <T extends Comparable<? super T>>
boolean disjoint2(List<? extends T> list1, List<? extends T>list2){
for(T x: list1){
if(Collections.binarySearch(list2, x)>=0){
return false;
}
}
return true;
}
emptyIterator metodu
İmzası
şöyle.
public static <T> Iterator<T> emptyIterator();
Boş bir Iterator döner. Şöyle
yaparız.
Iterator<String> iterator = Collections.emptyIterator();
emptyList metodu
Metodun içi
şöyledir
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
Örnek
Şöyle
yaparız. Immutable bir boş liste dönerç
List<String> list = Collections.<String>emptyList();
emptyListIterator metodu
İmzası
şöyle.
public static <T> ListIterator<T> emptyListIterator();
emptyMap metodu
Açıklaması
şöyle. Bu metod ile Map.of() benzer iş yaparlar. Fark olarak bu metod null key alabilirken, diğeri
alamaz.
Returns an empty map (immutable). This map is serializable.
emptySet metodu
İmzası
şöyle.
public static final <T> Set<T> emptySet();
frequency metoduCollections.frequency yazısına taşıdım
list metodu
Enumeration parametreden List
yaratır.
max metodu
Şöyle
yaparız.
List<Tuple<Integer, String>> list = ...;
Tuple<Integer, String> largestTuple = Collections.max(list,
Comparator.comparingInt(t -> t.x));
nCopies metodu
Açıklaması
şöyle. Aynı nesneden n tane doldurulmuş bir liste döner.
Returns an immutable list consisting of n copies of the specified object.
Örnek
Şöyle
yaparız.
Integer[] copies = Collections.nCopies(copiesCount, value)
.toArray(new Integer[copiesCount]);
Örnek
Şöyle
yaparız.
// say hello 100 times
System.out.println(String.join("", Collections.nCopies(100, "hello")));
Örnek
Şöyle
yaparız
Collections.nCopies (100, Boolean.FALSE).stream()...
Örnek
Listeye yeni bir nesne daha eklemek istiyorsak şöyle
yaparız.
List<String> mutable = new ArrayList<>(Collections.nCopies(10, "Hi"));
newHashMap metodu
Collections.newHashMap(int numMappings)
This creates a new, empty HashMap suitable for the expected number of mappings. The map uses a default load factor of 0.75, and its initial capacity is typically large enough to accommodate the expected number of mappings without requiring resizing.
newHashSet metodu
Collections.newHashSet(int numElements)
This creates a new, empty HashSet suitable for the expected number of elements. The set also uses a default load factor of 0.75, with an initial capacity that can accommodate the expected number of elements efficiently.
newHashSet
newSequencedSetFromMap metodu
Collections.newSequencedSetFromMap(SequencedMap<E, Boolean> map)
This method returns a SequencedSet backed by the specified SequencedMap. The resulting set maintains the ordering, concurrency, and performance characteristics of the backing map. This enables developers to obtain a SequencedSet implementation corresponding to any SequencedMap implementation.
newSetFromMap metodu
Örnek
Şöyle
yaparız.
Set<String> set = Collections.newSetFromMap(new LinkedHashMap<>(16, 0.75f, true));
Örnek
Şöyle
yaparız.
// get IdentytitySet wich wrap IdentityHashMap
Set<Person> set = Collections.newSetFromMap( new IdentityHashMap<>() )
reverse metodu
Verilen diziyi tersine çevirir.
Örnek
Şöyle
yaparız.
List<String> list = new ArrayList<String>();
list2.addAll(...);
...
Collections.reverse(list);
Örnek
Şöyle
yaparız.
Stack<Character> stack = ...
Collections.reverse (stack);
reverseOrder metodu
Sıralamayı terse çeviren bir comparator
döndürür.
Map<Float, String> mylist = new HashMap<>();
...
SortedSet<Float> orderlist = new TreeSet<Float>(Collections.reverseOrder());
orderList.addAll(mylist.keySet());
rotate metodu
shuffle metodu - Collection
Şöyle
yaparız.
List<Tuple<Integer, String>> list = ...;
Collections.shuffle(list);
shuffle metodu - Collection + Random
Şöyle
yaparız.
byte seed[] = new byte[...];
Random rnd = new SecureRandom(seed);
Collections.shuffle(deck, rnd);
shuffle metodu - List + RandomGenerator
Java 21 ile geliyor. Açıklaması
şöyle
This method randomly permutes the elements of the specified list using the provided source of randomness. The permutations occur with equal likelihood, assuming a fair source of randomness.
singleton metodu
Bir set döndürür. Metodun içi
şöyle.
public static <T> Set<T> singleton(T o) {
return new SingletonSet<>(o);
}
Şöyle
yaparız.
public Iterable<Board> solution() {
return Collections.singleton(board);
}
singletonMap metodu
public static <K,V> Map<K,V> singletonMap(K key, V value) {
return new SingletonMap<>(key, value);
}
Returns an immutable map, mapping only the specified key to the specified value. The returned map is serializable.
Örnek
Map'i güncellemeye çaılışınca exception fırlatılır. Şu kod hatalı
Collections.singletonMap("k", "v").computeIfAbsent("k", k -> "v" );
sort metodu
Sıralamak için iki yöntem var. Ya nesnemiz Comparable arayüzünü gerçekleştirmeli, ya da Comparator kullanmalı.Hangisini kullanırsak kullanalım, compare işleminin sonucu <0, =0, veya >0 bir değer dönmeli. Ben bu tanımı pek sevmiyorum. Genellikle -1, 0, 1 döndürmeye çalışıyorum.
sort metodu - List
Not 1: Bazı veri yapılarının kendi sort metodları var. Örneğin Arrays.sort() veya list.sort()
Örnek
Şöyle
yaparız
list.sort(Comparator.comparing(Item::getName));
Not 2: Java 8 ile gelen paralel sort bir seçenek olarak
düşünülebilir.
List<Point> pixels = ...
// Java 7 sorting
Collections.sort(pixels, comparator);
// Java 8 sorting
pixels = pixels.stream().parallel().
sorted(comparator).collect(Collectors.toList());
Metodun imzası
şöyle.
public static <T extends Comparable<? super T>> void sort(List<T> list)
1. Comparable Kullanarak
Nesne Comparable arayüzünü
gerçekleştirsin.
public class Foo implements Comparable<Foo> {
@Override
public int compareTo(Foo f) {
return ...
}
...
}
Şöyle
yaparız.
List<Foo> list = ...;
Collections.sort (list);
sort metodu - List + Comparator
Açıklaması
şöyle.
This implementation defers to the List.sort(Comparator) method using the specified list and comparator.
Metodun içi
şöyle.
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
1. Lambda Kullanarak
Elimizdeki nesneleri isimlerine göre sıralamak istiyor olalım. Lambda ile şöyle
yaparız.
Collections.sort(list,(a1,a2) -> (a1.getName().compareTo(a2.getName())));
2. Comparator Kullanarak
Eğer Comparator kullanmak istersek şöyle
yaparız.
Collections.sort(list, Comparator.comparing(Item::getName));
swap metodu
Belirtilen konumlardaki elemanları yer değiştirir. İmzası
şöyledir.
swap(List<?> list, int i, int j)
Metodun içi şuna
benzer.
public static void swap(List<?> list, int i, int j) {
final List l = list;
l.set(i, l.set(j, l.get(i)));
}
Şöyle
yaparız.
List<String> listOfStrings = new ArrayList<>();
listOfStrings.add("a");
listOfStrings.add("b");
listOfStrings.add("c");
listOfStrings.add("d");
Collections.swap(listOfStrings, 0, 1);
synchronizedCollection metodu
public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
return new SynchronizedCollection<T>(c);
}
List<Date> lst = ...
Collection<Date> synchedLst = Collections.syncrhonizedCollection(lst);
Bu metod sayesinde nesnemizi syncronized blokları içine almak zorunda
kalmayız.
List lst = LinkedList();
synchronized (lst) {
lst.add... // do some work lst.set... lst.remove...}
synchronizedList metodu
Metodun içi
şöyle.
public static <T> List<T> synchronizedList(List<T> list) {
return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList<T>(list) :
new SynchronizedList<T>(list));
}
Şöyle
yaparız.
List list = Collections.synchronizedList(new ArrayList());
list parametresi ArrayList ise
SynchronizedRandomAccessList Sınıfı döner.
Değilse SynchronizedList döner. Her iki sınıf ta tüm public metodlarında bir kilit
kullanır.
synchronizedMap metodu
Şöyle
yaparız.
Map<K, V> view = Collections.synchronizedMap (...);
Kendi içindeki private static SynchronizedMap sınıfını döner. Metodun içi
şöyle
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
return new SynchronizedMap<>(m);
}
SynhronizedMap sınıfının constructor metodları
şöyle.
SynchronizedMap(Map<K,V> m) {
this.m = Objects.requireNonNull(m);
mutex = this;
}
SynchronizedMap(Map<K,V> m, Object mutex) {
this.m = m;
this.mutex = mutex;
}
SynchronizedMap nesnenin tüm public metodlarında bir kilit kullanılır. Örneğin toString metodu
şöyle.
public String toString() {
synchronized (mutex) {return m.toString();}
}
unmodifiableCollection metodu
Collections Unmodifiable Sınıfları yazısına taşıdım.
unmodifiableList metodu
Collections Unmodifiable Sınıfları yazısına taşıdım.
unmodifiableMap metoduCollections Unmodifiable Sınıfları yazısına taşıdım.