数据结构与算法——Java常用api

1. 栈Stack、双端队列Deque

  • 栈不被推荐使用
Stack<Character> stack=new Stack<Character>();
stack.push('c'); // 入栈
char c=stack.peek(); // 查看栈顶元素
stack.pop(); // 出栈

class Stack<E> extends Vector<E> {}
  • 推荐使用Deque
  • ArrayDeque实现:循环数组,也就是说数组的任何一点都可能被看作起点或者终点
  • LinkedList实现:双向链表结构
Deque<Integer> Q=new ArrayDeque<Integer>();
Deque<Integer> Q=new LinkedList<Integer>();
//向尾部插入元素
Q.addLast(x);
//向头部插入元素
Q.addFirst(x);
//获取元素
Q.getFirst();
Q.getLast();
//获取并移除元素
Q.removeFirst();
Q.removeLast();

2. HashSet

Set<Integer> set=new HashSet<>();
boolean flag=set.contains(n); // 检查是否有重复元素
set.add(n); // 将不重复元素添加进去
int size=set.size();
set.remove(Object o); // 移除元素

3. HashMap

Map<Integer,String> map=new HashMap<>();
map.put(key, value); // 添加元素
boolean flag=map.containsKey(key); // 包含key
String value=map.get(key); // 依据key获取value
String value=map.getOrDefault(key, defaultValue); // key存在,获取value;不存在,添加默认value
int size=map.size();

Map<String,Integer> map=new HashMap<String,Integer>(){{
	put("One", 1);
	put("Two", 2);
	put("Three", 3);
}};

for (Map.Entry<String, Integer> entry : map.entrySet()) {
	System.out.println(entry.getKey());
	System.out.println(entry.getValue());
}


String[] strs = {"a", "b", "a", "c"};
Map<String, List<Integer>> map = new HashMap<>();
// 笨办法:
for (int i = 0; i < strs.length; i ++) {
	String str = strs[i];
	if (!map.containsKey(str)) {
		map.put(str, new ArrayList<>());
	}
	map.get(str).add(i);
}
// 优化1:
for (int i = 0; i < strs.length; i ++) {
	String str = strs[i];
	map.putIfAbsent(str, new ArrayList<>()); // 如果key对应的value不存在,先插入value
	map.get(str).add(i);
}
// 优化2:
for (int i = 0; i < strs.length; i ++) {
	String str = strs[i];
	map.compute(str, (k, v) -> v == null ? new ArrayList<>(1) : v).add(i);
}
// 优化3:
for (int i = 0; i < strs.length; i ++) {
	String str = strs[i];
	map.computeIfAbsent(str, k -> new ArrayList<>(1)).add(i);
}
// 详情见:https://segmentfault.com/a/1190000007838166

4. List

List<Integer> list=new ArrayList<>();
list.add(element);
list.get(index);
list.size();
list.add(index,element);

list.sort(new Comparator<Integer>() {
	@Override
	public int compare(Integer o1, Integer o2) {//逆序:从大到小
		if(o1>o2) return -1;
		else if(o1<o2) return 1;
		else return 0;
	};
});
Collections.sort(list, new Comparator<Integer>() {
	@Override
	public int compare(Integer o1, Integer o2) {//逆序:从大到小
		if(o1>o2) return -1;
		else if(o1<o2) return 1;
		else return 0;
	};
});

5. Queue

Queue<Integer> queue=new LinkedList<>();
queue.offer(e); // 插入一个元素
Integer e=queue.poll(); // 移除和返回队列的头
Integer e=queue.peek(); // 返回但不移除队列的头

6. PriorityQueue

pqueue.offer();//插入
pqueue.peek();//返回
pqueue.poll();//返回并移除
pqueue.remove(Object o);


// 从大到小排序,堆顶元素为最大值
PriorityQueue<Integer> pqueue=new PriorityQueue<Integer>(
		new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				if(o1>o2) return -1;
				else if(o1<o2) return 1;
				else return 0;
			}
		}
);
// 等价于
PriorityQueue<Integer> priorityQueue=new PriorityQueue<>((o1, o2) -> o2 - o1);
// 从小到大排序,堆顶元素为最小值
PriorityQueue<Integer> pqueue=new PriorityQueue<Integer>(
		new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				if(o1>o2) return 1;
				else if(o1<o2) return -1;
				else return 0;
			}
		}
);
// 等价于
PriorityQueue<Integer> priorityQueue=new PriorityQueue<>((o1, o2) -> o1 - o2);


// 按照数组第二个位置的元素从大到小排序,堆顶元素为第二个位置取最大值的数组
PriorityQueue<int[]> pqueue=new PriorityQueue<>(
		new Comparator<int[]>() {
			@Override
			public int compare(int[] o1, int[] o2) {
				if(o1[1]>o2[1]) return -1;
				else if(o1[1]<o2[1]) return 1;
				else return 0;
			}
		}
);
// 等价于
PriorityQueue<int[]> pqueue=new PriorityQueue<>((o1, o2) -> o2[1] - o1[1]);


// 数组第一个元素从小到大排序,如果第一个元素相同,第二个元素从大到小排序
PriorityQueue<int[]> pqueue=new PriorityQueue<>((o1, o2) -> o1[0] == o2[0] ? o2[1] - o1[1] : o1[0] - o2[0]);


// 按照My.class的getNum()从大到小排序,堆顶元素为最大值
PriorityQueue<My> pqueue=new PriorityQueue<My>(
		new Comparator<My>() {
            @Override
            public int compare(My o1, My o2) {
                if(o1.getNum()>o2.getNum()) return -1;
                else if(o1.getNum()<o2.getNum()) return 1;
                else return 0;
            }
        }
);
// 等价于
PriorityQueue<My> pqueue=new PriorityQueue<My>((o1, o2) -> o2.getNum() - o1.getNum());


// 按照Map的value从大到小排序,堆顶元素为最大值value对应的Entry(结构:key=value)
PriorityQueue<Map.Entry<Integer, Integer>> priorityQueue = new PriorityQueue<>(
		new Comparator<Map.Entry<Integer, Integer>>() {
         	@Override
            public int compare(Map.Entry<Integer, Integer> e1, Map.Entry<Integer, Integer> e2) {
            	return e2.getValue() - e1.getValue();
            }
		}
);
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<5;i++) {
	map.put(i,i+2);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
	priorityQueue.add(entry);
}

7. 数组Arrays

int[] nums=new int[5];
int[] nums=new int[] {1,2,3,4,5};
Arrays.fill(nums,Integer.MAX_VALUE);
Arrays.asList(nums);
Arrays.sort(nums);
Arrays.copyOfRange(nums, fromIndex, toIndex);

//二维数组排序按照第二个元素排序
int[][] nums=new int[][]{{1,3},{2,4},{3,2}};
Arrays.sort(nums, new Comparator<int[]>(){
	public int compare(int[] a, int[] b){
               return b[1]-a[1];
	}
});

8. 常用类型转换

  • String <---> Char
String str = String.valueOf('c');
char c=str.charAt(index) //返回在index位置的char字符。(返回值:char )
char[] chars=str.toCharArray( ) //将String 转化为 字符串数组。(返回值:char[] ) 
  • String数组 <---> List
String[] strs1= new String[]{"Tom", "Bob", "Jane"};
List<String> strList= Arrays.asList(strs1);
String[] strs2=new String[strList.size()];
strList.toArray(strs2);
  • int数组 <---> List
int[] data = {4, 5, 3, 6, 2, 5, 1};
List<Integer> list1 = Arrays.stream(data).boxed().collect(Collectors.toList());
int[] arr1 = list1.stream().mapToInt(Integer::valueOf).toArray();
  • 数组 <---> Set
String[] strs1= new String[]{"Tom", "Bob", "Jane"};
Set<String> set = new HashSet<String>(Arrays.asList(strs1)); 
String[] strs2=new String[set.size()];
set.toArray(strs2);
  • Set <---> List
List<String> list=new ArrayList<String>();
list.add("a");
list.add("b");
list.add("a");
Set<String> set=new HashSet<String>(list);
List<String> newlist=new ArrayList<String>(set);
  • List<int[]> <---> int[][]
List<int[]> list= new ArrayList<>();
list.add(new int[] {1,2});
list.add(new int[] {3,4});
int[][] arrs= list.toArray(new int[0][]);

详细查看:https://www.cnblogs.com/zhihaospace/p/12547294.html
  • 其他

java中List, Integer[], int[]的相互转换

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值