Pure Java – 74 Generics & Collections – Map – 02

Merhaba Arkadaslar,
Bu bolumde Map konusuna devam edecegiz. java.util.TreeMap ve Backed Collection konusunu inceleyecegiz.
Hatirlayacagimiz gibi java.util.TreeMap sorted ve ordered ozellige sahiptir. java.util.Treemap sinifi java.util.Navigable arabirimini uygulamaktadir.

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{...}

Ornek kod ile baslayalim , natural order’a gore key’e gore siralama yapacaktir. String key’ekledikten sonra , Integer tipte bir key ekleyemeyiz. Bu durumda String ile Integer arasinda siralama yapamayacaktir.Ilk hangi tip eklersek o tipte key’leri eklemeye devam etmeliyiz.

import java.util.Map;
import java.util.TreeMap;

public class TreeMapTest {

	public static void main(String[] args) {
		Map treeMap = new TreeMap();

		treeMap.put("key1", "value1");
		treeMap.put("key5", "value5");
		treeMap.put("key2", "value2");
		treeMap.put("key3", "value3");

		// treeMap.put(1, "java.lang.ClassCastException");

		for (Object key : treeMap.keySet()) {
			System.out.println(key + " " + treeMap.get(key));
		}

	}
}

Hatirlayacagimiz gibi Wrapper siniflar ve String sinifi Comparable arabirimini uygulamaktadir. Bu nedenle TreeMap’te kullanabiliyoruz. Eger kendi olusturdugumuz bir sinifi TreeMap’te key olarak kullanmak istersek bu durumda Comparable arabirimini uygulamalidir. Aksi takdirde java.lang.ClassCastException hatasi verecektir.

import java.util.TreeMap;

class Animal {

}

class Car implements Comparable {

	public Car(String hp, String brand, Integer price) {
		super();
		this.hp = hp;
		this.brand = brand;
		this.price = price;
	}

	String hp;

	@Override
	public String toString() {
		return "Car [hp=" + hp + ", brand=" + brand + ", price=" + price + "]";
	}

	String brand;
	Integer price;

	@Override
	public int compareTo(Car car) {
		return price.compareTo(car.price);
	}
}

public class TreeMapCarTest {

	public static void main(String[] args) {
		Animal animal = new Animal();
		TreeMap<Animal, String> animalTreeMap = new TreeMap<Animal, String>();
		// animalTreeMap.put(animal, "java.lang.ClassCastException");
		// key olarak Comparable olan siniflari kullanabiliriz. Yani bu durumda
		// Animal sinifi Comparable olmali aksi durumda calisma zamaninda hata
		// verecektir.

		Car ford = new Car("50", "ford", 100);
		Car ford2 = new Car("150", "ford", 500);
		Car ford3 = new Car("250", "ford", 1000);

		TreeMap<Car, String> carTreeMap = new TreeMap<Car, String>();

		carTreeMap.put(ford, "cheap car");
		carTreeMap.put(ford3, "fast car");
		carTreeMap.put(ford2, "nice car");

		for (Car key : carTreeMap.keySet()) {
			System.out.println(key + " -->" + carTreeMap.get(key));
		}

	}
}

TreeMap sinifi ceilingEntry , ceilingKey , higherEntry , higherKey , floorEntry , floorKey , lowerEntry , lowerKey metotlarini inceleyelim.

import java.util.Map.Entry;
import java.util.TreeMap;

public class TreeMapNavigateTest {

	public static void main(String[] args) {
		TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();

		treeMap.put(1, "one");
		treeMap.put(2, "two");

		treeMap.put(30, "thirty");
		treeMap.put(40, "forty");
		treeMap.put(50, "fifty");

		treeMap.put(70, "seventy");
		treeMap.put(100, "hundred");

		// ceilingEntry(key)  minimum >=key olan Entry dondurur.
		// #### ceilingEntry
		Entry<Integer, String> ceilingEntry = treeMap.ceilingEntry(40);
		Integer ceilingEntryKey = ceilingEntry.getKey();
		String ceilingEntryValue = ceilingEntry.getValue();

		// ceilingKey  minimum>=key olan key degerini dondurur.
		// #####ceilingKey
		Integer ceilingKey = treeMap.ceilingKey(40);

		// ceiling metotlari icin >= soz konusudur. 40 key degerine sahip bir
		// eleman oldugu icin ilgili key/value alacaktir.
		System.out.println("ceilingEntryKey: " + ceilingEntryKey);
		System.out.println("ceilingEntryValue: " + ceilingEntryValue);
		System.out.println("ceilingKey: " + ceilingKey);

		// higherEntry(key)  minimum>key olan Entry dondurur.
		// #### higherEntry
		Entry<Integer, String> higherEntry = treeMap.higherEntry(40);
		Integer higherEntryKey = higherEntry.getKey();
		String higherEntryValue = higherEntry.getValue();

		// higherKey  minimum>key olan key degerini dondurur.
		// Burada buyuk esit yok!
		// ### higherKey
		Integer higherKey = treeMap.higherKey(40);

		// higher metotlari > soz konusudur. 40 degerini almaz 40 degerinden
		// buyuk olan ilk 50 oldugu icin bu elemani alir.
		System.out.println("higherEntryKey: " + higherEntryKey);
		System.out.println("higherEntryKey: " + higherEntryValue);
		System.out.println("higherKey: " + higherKey);

		// floorEntry(key)  maximum<=key olan Entry dondurur.
		Entry<Integer, String> floorEntry = treeMap.floorEntry(40);
		Integer floorEntryKey = floorEntry.getKey();
		String floorEntryValue = floorEntry.getValue();
		// floorKey maximum<=key olan key degerini dondurur.
		Integer floorKey = treeMap.floorKey(40);

		System.out.println("floorEntryKey: " + floorEntryKey);
		System.out.println("floorEntryValue: " + floorEntryValue);
		System.out.println("floorKey: " + floorKey);

		// lowerEntry(key) maximum lowerEntry = treeMap.lowerEntry(40);
		Integer lowerEntryKey = lowerEntry.getKey();
		String lowerEntryValue = lowerEntry.getValue();

		Integer lowerKey = treeMap.lowerKey(40);

		System.out.println("lowerEntryKey: " + lowerEntryKey);
		System.out.println("lowerEntryValue: " + lowerEntryValue);
		System.out.println("lowerKey: " + lowerKey);

	}
}

Simdi de TreeMap’te bulunan diger metotlari inceleyelim; firstEntry , lastEntry , pollFirstEntry , pollLastEntry , descendingMap , descendingKeySet

import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.TreeMap;
import java.util.Map.Entry;

public class TreeMapMoreNavigateTest {

	public static void main(String[] args) {
		TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();

		treeMap.put(1, "one");
		treeMap.put(2, "two");

		treeMap.put(30, "thirty");
		treeMap.put(40, "forty");
		treeMap.put(50, "fifty");

		treeMap.put(70, "seventy");
		treeMap.put(100, "hundred");

		Entry<Integer, String> firstEntry = treeMap.firstEntry();
		Integer firstKey = treeMap.firstKey();

		Entry<Integer, String> lastEntry = treeMap.lastEntry();
		Integer lastKey = treeMap.lastKey();

		System.out.println("firstKey:" + firstKey);
		System.out.println("lastKey:" + lastKey);

		// pollFirstEntry , ilk elemani getirir ve siler.
		Entry<Integer, String> pollFirstEntry = treeMap.pollFirstEntry();
		// pollLastEntry , son elemani getirir ve siler.
		Entry<Integer, String> pollLastEntry = treeMap.pollLastEntry();

		firstKey = treeMap.firstKey();
		lastKey = treeMap.lastKey();

		System.out.println("after poll firstKey:" + firstKey);
		System.out.println("after poll lastKey:" + lastKey);

		for (Integer key : treeMap.keySet()) {
			System.out.println("key : " + key + " value : " + treeMap.get(key));
		}

		//descendingMap geriye NavigableMap dondururur.NavigableMap bir arabirimdir.
		//SortedMap arabirimini kalitir , SortedMap de Map arabirimini kalitir.
		// Bu metot siiralamayi tersten yapar ve geriye DescendingSubMap tipinde obje dondurur.
		
		NavigableMap<Integer, String> descendingMap = treeMap.descendingMap();
		System.out.println("descendingMap");
		for (Integer key : descendingMap.keySet()) {
			System.out.println("key : " + key + " value : " + treeMap.get(key));
		}

		NavigableSet navigableDescendingKeySet = treeMap.descendingKeySet();
		System.out.println("navigable descending keyset");
		for(Integer key: navigableDescendingKeySet){
			System.out.println(key);
		}
		
	}
}

java.util.TreeMap icin kullandigimiz bu metotlari benzer sekilde java.util.TreeSet sinifi icin de kullanabiliriz.

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

public class TreeSetTest {

	public static void main(String[] args) {
		TreeSet treeSet = new TreeSet();

		treeSet.add(10);
		treeSet.add(20);
		treeSet.add(30);
		treeSet.add(40);

		Integer first = treeSet.first();
		Integer last = treeSet.last();

		Integer ceiling = treeSet.ceiling(30);
		Integer higher = treeSet.higher(30);

		Integer floor = treeSet.floor(30);
		Integer lower = treeSet.lower(30);

		NavigableSet navigableDescendingSet = treeSet.descendingSet();
		Iterator descendingIterator = treeSet.descendingIterator();

		System.out.println("first:" + first);
		System.out.println("last:" + last);

		System.out.println("ceiling:" + ceiling);
		System.out.println("higher:" + higher);

		System.out.println("floor:" + floor);
		System.out.println("lower:" + lower);

		System.out.println("treeset");
		for (Integer i : treeSet) {
			System.out.println(i);
		}

		System.out.println("navigable descendingset");
		for (Integer i : navigableDescendingSet) {
			System.out.println(i);
		}
		System.out.println("descending iterator");
		while (descendingIterator.hasNext()) {
			System.out.println(descendingIterator.next());
		}
	}
}

Son olarak backed collection yapisini inceleyelim. headMap , tailMap ,subMap gibi metotlari inceleyelim.

import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;

public class BackedMap {

	public static void main(String[] args) {
		TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();

		treeMap.put(1, "one");
		treeMap.put(2, "two");

		treeMap.put(30, "thirty");
		treeMap.put(40, "forty");
		treeMap.put(50, "fifty");

		treeMap.put(70, "seventy");
		treeMap.put(100, "hundred");

		SortedMap<Integer, String> headMapExclusive = treeMap.headMap(30);
		// headMap(30) varsayilan olarak exclusive calisir.

		/*
		 * public SortedMap<K,V> headMap(K toKey) {
		 * return headMap(toKey, false);
		 * }
		 */

		// headMap exclusive
		System.out.println("headMap exclusive");
		for (Integer key : headMapExclusive.keySet()) {
			System.out.println(key + " " + headMapExclusive.get(key));
		}

		System.out.println("headMap inclusive");
		// boolean arguman alan overloaded metotlar NavigableMap donmektedir.
		// public interface NavigableMap<K,V> extends SortedMap<K,V> { }
		// NavigableMap yerine SortedMap de kullanabiliriz.
		// NavigableMap IS-A SortedMap
		NavigableMap<Integer, String> headMapInclusive = treeMap.headMap(30, true);
		for (Integer key : headMapInclusive.keySet()) {
			System.out.println(key + " " + headMapInclusive.get(key));
		}

		/*
		 * public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
		 * return new AscendingSubMap(this,
		 * true, null, true,
		 * false, toKey, inclusive);
		 * }
		 */

		System.out.println();

		SortedMap<Integer, String> tailMapInclusive = treeMap.tailMap(30);
		// tailMap(30) varsayilan olarak inclusive calisir.

		/*
		 * public SortedMap<K,V> tailMap(K fromKey) {
		 * return tailMap(fromKey, true);
		 * }
		 */

		System.out.println("tailMapInclusive ");
		for (Integer key : tailMapInclusive.keySet()) {
			System.out.println(key + " " + tailMapInclusive.get(key));
		}

		System.out.println("tailMap exclusive ");
		NavigableMap<Integer, String> tailMapexclusive = treeMap.tailMap(30, false);
		for (Integer key : tailMapexclusive.keySet()) {
			System.out.println(key + " " + tailMapexclusive.get(key));
		}

		System.out.println();

		System.out.println("subMap");
		SortedMap<Integer, String> subMap = treeMap.subMap(30, 70);
		// varsayilan olarak [dahil-haric) seklindedir. inclusive-exclusive
		for (Integer key : subMap.keySet()) {
			System.out.println(key + " " + subMap.get(key));
		}

		/*
		 * public SortedMap<K,V> subMap(K fromKey, K toKey) {
		 * return subMap(fromKey, true, toKey, false);
		 * }
		 */

		System.out.println("subMap2");
		NavigableMap<Integer, String> subMap2 = treeMap.subMap(30, true, 70, true);

		for (Integer key : subMap2.keySet()) {
			System.out.println(key + " " + subMap2.get(key));
		}
	}
}

Benzer sekilde java.util.TreeSet icin headSet , tailSet ve subSet metotlari kullanilabilir.

import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;

public class BackedSet {

	public static void main(String[] args) {
		TreeSet treeSet = new TreeSet();

		treeSet.add(1);
		treeSet.add(2);

		treeSet.add(30);
		treeSet.add(40);
		treeSet.add(50);

		treeSet.add(70);
		treeSet.add(100);

		SortedSet headSetExclusive = treeSet.headSet(30);
		/*
		 * public SortedSet headSet(E toElement) {
		 * return headSet(toElement, false);
		 * }
		 */

		System.out.println("headSet exlusive");
		for (Integer i : headSetExclusive) {
			System.out.println(i);
		}

		NavigableSet headSetInclusive = treeSet.headSet(30, true);

		System.out.println("headSet Inclusive");
		for (Integer i : headSetInclusive) {
			System.out.println(i);
		}
		SortedSet tailSetInclusive = treeSet.tailSet(30);
		/*
		 * public SortedSet tailSet(E fromElement) {
		 * return tailSet(fromElement, true);
		 * }
		 */

		System.out.println("tailSet Inclusive");
		for (Integer i : tailSetInclusive) {
			System.out.println(i);
		}

		NavigableSet tailSetExclusive = treeSet.tailSet(30, false);
		System.out.println("tailSe tExclusive");
		for (Integer i : tailSetExclusive) {
			System.out.println(i);
		}

		SortedSet subSet = treeSet.subSet(30, 70);
		/*
		 * public SortedSet subSet(E fromElement, E toElement) {
		 * return subSet(fromElement, true, toElement, false);
		 * }
		 */

		System.out.println("subSet inclusive-exlusive");
		for (Integer i : subSet) {
			System.out.println(i);
		}

		NavigableSet subSet2 = treeSet.subSet(30, true, 70, true);
		System.out.println("subset2 inclusive-inclusive");
		for (Integer i : subSet2) {
			System.out.println(i);
		}
	}
}

Backed Collection’a eleman eklerken ya da cikartirken dikkat edilmesi gereken bazi noktalar yer almaktadir.

  • Orijinal TreeMap/TreeSet e eleman ekledigimizde/sildigimizde eger backed collection’in sinirlari icerisindeyse backed collection a da ekler/siler.
  • Backed Collection a eleman ekledigimiz/sildigimiz elemanlar orijinal TreeMap/TreeSet ten de silinir/eklenir.
package treemap;

import java.util.NavigableMap;
import java.util.TreeMap;

public class AddBackedMap {

	public static void main(String[] args) {
		TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();

		treeMap.put(1, "one");
		treeMap.put(2, "two");

		treeMap.put(30, "thirty");
		treeMap.put(40, "forty");
		treeMap.put(50, "fifty");

		treeMap.put(70, "seventy");
		treeMap.put(100, "hundred");

		NavigableMap<Integer, String> subMap = treeMap.subMap(30, true, 70, true);

		System.out.println("subMap");
		for (Integer key : subMap.keySet()) {
			System.out.println(key + " " + subMap.get(key));
		}

		treeMap.put(60, "sixty");
		// treeMap e 60 degerini ekledik bu deger subMap in sinirlari icinde
		// ayni zamanda subMap'e de ekler.
		treeMap.put(1000, "thousand");
		// treeMap e eklenen 1000 degeri subMap e eklenmez. subMap in sinirlari
		// disindadir.

		subMap.put(65, "sixty five");
		// subMap'e ekledigimiz bu deger treeMap e de eklenir.

		// subMap.put(80, "exception");
		// subMap e sinir disinda key ekleyemeyiz. [30,70] arasinda eklenebilir.
		// java.lang.IllegalArgumentException: key out of range

		System.out.println("after subMap");
		for (Integer key : subMap.keySet()) {
			System.out.println(key + " " + subMap.get(key));
		}

		System.out.println("after treeMap");
		for (Integer key : treeMap.keySet()) {
			System.out.println(key + " " + treeMap.get(key));
		}

	}
}

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *