ArrayList 與 HashMap 範例

URL Link //n.sfs.tw/13298

2019-05-16 10:56:47 By igogo

 

 

職稱是根據一組字串由逗號分隔帶回數字代碼例如 “40,80,60"  

數字代表的是不同的職稱, 考量將來可能又有新的職稱, 所以另外寫一個對照

 

分別用arraylist 及hashmap 來加入職稱範例

public static void main(String[] args) {

 String titleIds = "40,80,100";
        List<String> titles = new ArrayList<>();

        Arrays.asList(titleIds.split(",")).forEach(id->{
            titles.add(getTitle(Integer.valueOf(id)));
        });

        titles.forEach(title -> System.out.printf(title));


        HashMap<Integer,String> hashMap = new HashMap<>();
        Arrays.asList(titleIds.split(",")).forEach(id->hashMap.put(Integer.valueOf(id),getTitle(Integer.valueOf(id))));

        hashMap.forEach((k,v)-> System.out.println(k+":"+v));
        //直接由hashMap的key 取得值
        System.out.println(hashMap.get(40));
        
}

    public String getTitle(Integer id) {
        String title = "";

        if (id == 40 ) {
            title = "資訊組長";
        }
        if (id == 50) {
            title = "校長";
        }
        if (id == 100) {
            title = "工友";
        }
        return title;

    }