代碼實(shí)現(xiàn):
package?day18_TreeMap;import?java.util.Scanner;import?java.util.Set;import?java.util.TreeMap;public?class?TreeMapTest?{????public?static?void?main(String[]?args)?{????????//?TODO?Auto-generated?method?stub????????//定義一個(gè)字符串(可以改進(jìn)為鍵盤錄入)????????Scanner?sc?=?new?Scanner(System.in);????????System.out.println("請輸入字符串:");????????String?line=sc.nextLine();????????//定義一個(gè)TreeMap集合????????TreeMap<Character,?Integer>?tm?=?new?TreeMap<Character,Integer>();????????//把字符串轉(zhuǎn)換為字符數(shù)組????????char?[]?chs=line.toCharArray();????????//遍歷字符數(shù)組,得到每一個(gè)字符????????for(char?key:chs){????????????//拿剛才得到的字符作為鍵到集合中去找,看返回值????????????Integer?i=tm.get(key);????????????//判斷????????????if(i==null){????????????????//Null:說明該鍵不存在,就把該字符作為鍵,1作為值存儲(chǔ)????????????????tm.put(key,?1);????????????}else{????????????????//不是Null:說明該鍵存在,就把值加1,然后重寫存儲(chǔ)該鍵和值????????????????i++;????????????????tm.put(key,?i);????????????}????????}????????//定義字符串緩沖區(qū)變量????????StringBuilder?sb?=?new?StringBuilder();????????//遍歷集合,得到鍵和值,進(jìn)行按照要求拼接????????Set<Character>?set?=?tm.keySet();????????for(Character?key:set){????????????Integer?value=tm.get(key);????????????sb.append(key).append("(").append(value).append(")");????????}????????//把字符串緩沖區(qū)轉(zhuǎn)換為字符串輸出????????String?result=sb.toString();????????System.out.println("result:"+result);????}}
以上就是天津卓眾教育java培訓(xùn)機(jī)構(gòu)的小編針對“Java編程分享,treemap實(shí)現(xiàn)具體實(shí)現(xiàn)Demo”的內(nèi)容進(jìn)行的回答,希望對大家有所幫助,如有疑問,請?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。