2017-05-23 2 views
1

Employee_id (int),Employee_name (String) & Employee_Salary(long)をコレクションに保存します。そのうちEmployee_idは常に昇順にソートされた一意の&である必要があります。 Employee_namesを複製することができます。 どのJavaコレクションを使用することができますか?&どうすればこの基本的なプログラムができますか?collection_typeを使用できる以下の要件で従業員の詳細を保存するには?

ありがとうございます。

+3

キーが従業員IDの場合、 'TreeMap 'を使うことができます。 – Eran

+0

EmployeeオブジェクトにはEmployee_nameとEmployee_salaryが含まれます。 –

+0

はい、従業員IDも含めることにします。 – Eran

答えて

1

使用して、ここでTreeMapは一例です。

JAVA

import java.util.TreeMap; 
import java.util.Set; 
import java.util.Iterator; 
import java.util.Map; 

... 

/* This is how to declare TreeMap */ 
    TreeMap<Integer, String> tmap = 
     new TreeMap<Integer, String>(); 

    /*Adding elements to TreeMap*/ 
    tmap.put(1, "Data1"); 
    tmap.put(23, "Data2"); 
    tmap.put(70, "Data3"); 
    tmap.put(4, "Data4"); 
    tmap.put(2, "Data5"); 

    /* Display content using Iterator*/ 
    Set set = tmap.entrySet(); 
    Iterator iterator = set.iterator(); 
    while(iterator.hasNext()) { 
    Map.Entry mentry = (Map.Entry)iterator.next(); 
    System.out.print("key is: "+ mentry.getKey() + " & Value is: "); 
    System.out.println(mentry.getValue()); 
    } 

ます。またHashMap使用することができます

+0

**ソート済み**は、 'HashMap'には適用されません。 – Sergey

0

私はEMPLOYEE_ID非重複を格納するHashMapを使用します(何ソートは適用されません)。 次を保存するために2つのHashMapをする必要があります: EMPLOYEE_ID、EMPLOYEE_NAME、Employee_Salary

//this will hold the id and name 
HashMap<Integer, String> employeeHM = new HashMap<>(); 
//this will hold the id of employeeHM's HashMap and the salary 
HashMap<Integer, Long> salaryHM = new HashMap<>(); 

@ThatAwesomeCoderは、HashMapのは、並べ替えを欠い、言ったように。これを克服するには、employeeHMからすべてのIDを読み取り、ソート関数を使用してArrayListコレクションにソートするループを作成します。

+0

HashMap も機能します。 –

0

従業員データをキーと値のペアとして格納する必要がある場合は、従業員IDを使用してTreeMapを一意のキーとして使用できます。それをセットの形で保存する必要がある場合は、Comparatorsを受け入れるTreesetのオーバーライドされたコンストラクタを使用するのはどうでしょうか?コンパレータ内では、比較ロジックを指定できます。ちょうど私の2セント..

関連する問題