接上文: 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<>(); //put map.put(2,5); map.put(1,2); //get int a=map.get(2); int b=map.get(1); System.out.println(a+","+b); System.out.println(map.get(11)); System.out.println(map); //size System.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<>(); //push stack.push(3); stack.push(4); stack.push(5); //pop int a=stack.pop(); int b=stack.pop(); System.out.println(a+" "+b); //peek:查看栈顶元素 System.out.println(stack.peek()); //isEmpty boolean 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<>(); //add boolean 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()); //isEmpty System.out.println(q.isEmpty()); } }