Metode Three Map

Rabu, 21 Januari 2009

Three Map Method.

Dalam contoh berikut, kami telah menggunakan metode TreeMap, toko-nya elemen yang di pohon dan pesanan dengan unsur berdasarkan nilai-nilai mereka. Pada contoh di sini kita telah menggunakan tombol dari elemen yang menunjukkan nilai-nilai elemen. Untuk mengambil kunci dan nilai-nilai menggunakan keySet () dan nilai-nilai () metode masing-masing.

Program ini menunjukkan data elemen kiri setelah mengeluarkan unsur tertentu dengan menentukan kunci-nya. Menggunakan metode iterator interface, kita dapat melintasi sebuah koleksi dari awal hingga selesai dan aman menghapus elemen dari yang Koleksi.

Berikut adalah kode program berikut ini:


import java.util.*;

public class TreeMapExample{
public static void main(String[] args) {
System.out.println("Tree Map Example!\n");
TreeMap tMap = new TreeMap();
//Addding data to a tree map
tMap.put(1, "Sunday");
tMap.put(2, "Monday");
tMap.put(3, "Tuesday");
tMap.put(4, "Wednesday");
tMap.put(5, "Thursday");
tMap.put(6, "Friday");
tMap.put(7, "Saturday");
//Rerieving all keys
System.out.println("Keys of tree map: " + tMap.keySet());
//Rerieving all values
System.out.println("Values of tree map: " + tMap.values());
//Rerieving the value from key with key number 5
System.out.println("Key: 5 value: " + tMap.get(5)+ "\n");
//Rerieving the First key and its value
System.out.println("First key: " + tMap.firstKey() + " Value: "
+ tMap.get(tMap.firstKey()) + "\n");
//Rerieving the Last key and value
System.out.println("Last key: " + tMap.lastKey() + " Value: "
+ tMap.get(tMap.lastKey()) + "\n");
//Removing the first key and value
System.out.println("Removing first data: " + tMap.remove(tMap.firstKey()));
System.out.println("Now the tree map Keys: " + tMap.keySet());
System.out.println("Now the tree map contain: " + tMap.values() + "\n");
//Removing the last key and value
System.out.println("Removing last data: " + tMap.remove(tMap.lastKey()));
System.out.println("Now the tree map Keys: " + tMap.keySet());
System.out.println("Now the tree map contain: " + tMap.values());
}
}



Output of this program:

C:\vinod\collection>javac TreeMapExample.java

C:\vinod\collection>java TreeMapExample
Tree Map Example!

Keys of tree map: [1, 2, 3, 4, 5, 6, 7]
Values of tree map: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
Key: 5 value: Thursday

First key: 1 Value: Sunday

Last key: 7 Value: Saturday

Removing first data: Sunday
Now the tree map Keys: [2, 3, 4, 5, 6, 7]
Now the tree map contain: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]

Removing last data: Saturday
Now the tree map Keys: [2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday, Wednesday, Thursday, Friday]

C:\vinod\collection>

0 komentar: