接上文:?7.16 Java基礎 | 集合框架(上)-CSDN博客
【1】Map集合
Map 集合是一種能存儲鍵值對的數據結構。它的主要功能是依據鍵(Key)來快速查找對應的值(Value)1、聲明
????????????????Map<Integer,Integer>map=new HashMap<>();? ? ?
2、常用方法
? ? ? ? put(key , value);
? ? ? ? get();
? ? ? ? size();
? ? ? ? entrySet() ;將Map集合的每個key-value轉換成一個Entry對象,并返回由所有的Entry對象組成的set集合
??? ? ?getOrdefault(key ,默認值); 獲取key對應的value,如果找不到key,則返回設置的默認值
?代碼示例:
import java.util.*; import java.util.Map.Entry; public class Map集合 {public static void main(String[] args) {Map<Integer,Integer>map=new HashMap<>();//putmap.put(2,5);map.put(1,2);//getint a=map.get(2);int b=map.get(1);System.out.println(a+","+b);System.out.println(map.get(11));System.out.println(map);//sizeSystem.out.println(map.size());//遍歷for(Entry<Integer,Integer>entry:map.entrySet()) {System.out.println(entry.getKey()+" "+entry.getValue());}int c=map.getOrDefault(15,12);System.out.println(c);} }
3、綜合應用
import java.util.*; import java.util.Map.Entry;public class test1 {public static void main(String[] args) {Scanner sc=new Scanner(System.in);int n=sc.nextInt();Map<Integer,Integer>map=new HashMap<>();for(int i=0;i<n;i++) {int a=sc.nextInt();map.put(a,map.getOrDefault(a,0)+1);}int max=0;for(Entry<Integer,Integer>entry:map.entrySet()) {max=Math.max(max, entry.getValue());}List<Integer>list=new ArrayList<>();//列表存儲出現次數為max的所有值for(Entry<Integer,Integer>entry:map.entrySet()) {if(entry.getValue()==max) {list.add(entry.getKey());}}Collections.sort(list);for(int x:list) {System.out.print(x+" ");}} }
【2】Stack棧
先進后出
1、聲明
?? ?Stack<Integer>stack=new Stack<>();? ? ? ? ? ? ? ? ??
2、方法
push()入棧
pop()? ?岀棧? ? ?
peek()? 查看棧頂元素? ? ?
isEmpty()判空
3 、代碼示例
import java.util.*; public class 棧 {public static void main(String[] args) {Stack<Integer>stack=new Stack<>();//pushstack.push(3);stack.push(4);stack.push(5);//popint a=stack.pop();int b=stack.pop();System.out.println(a+" "+b);//peek:查看棧頂元素System.out.println(stack.peek());//isEmptyboolean c=stack.isEmpty();System.out.println(c);} }
【3】Queue隊列
?1、聲明
?? ?Queue<Integer>q=new LinkedList<>();
2、方法
add()入隊
poll()出隊
peek()查看隊頭
isEmpty()判空
3、代碼示例
import java.util.*;public class 隊列 {public static void main(String[] args) {Queue<Integer>q=new LinkedList<>();//addboolean a=q.add(2);System.out.println(a);q.add(3);q.add(4);System.out.println(q);//poll 先進先出System.out.println(q.poll());//peek()System.out.println(q.peek());//isEmptySystem.out.println(q.isEmpty());} }