Java_基础用法

yql

HashMap 基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class HashMapExample{
/*
创建HashMap实例
*/
HashMap<String, Integer> map = new HashMap<>(); //空实例
HashMap<String, Integer> mapWithCapacity = new HashMap<>(16); //指定初始容量
HashMap<String, Integer> mapWithLoadFactor = new HashMap<>(16, 0.75f); //指定负载因子

//添加元素
map.put("apple", 1);

//获取元素
mp.get("apple");

//删除元素
mp.remove("apple");

//检查是否包含值或者value
boolean hasApple = map.containsKey("apple");
boolean hasValue = map.containsValue(1);

/*
遍历HashMap
*/
for(String key : map.keySet()){
System.out.println(key);
}

for(Integer value: map.values()){
System.out.println(value);
}

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

//获取默认值
Integer value = map.getOrDefault("pear", 0);

//替换元素
map.replace("apple", 10);

//批量操作: 可以使用putAll()方法将另一个Map中的所有键值对添加到当前的HashMap
HashMap<String, Integer> otherMap = new HashMap<>();
otherMap.put("grape", 4);
map.putAll(otherMap);

//清空
map.clear();

//使用compute和merge方法
map.compute("apple", (key, val)->(val == null) ? 1 : val + 1);
map.compute("num", (k, v) -> v * v); // 将值更新为原来的平方
map.merge("apple", 2, Integer::sum);

}

HashSet 基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class HashSetExample{
public static void main(String[] args){
HashSet<String> st = new HashSet<>();

//为hashset指定初始容量和负载因子
HashSet<String> st2 = new HashSet<>(16, 0.75f);

//添加元素
st.add("apple");
st.add("banana");

//移除元素
st.remove("banana");

//检查元素是否存在
if(st.contains("apple")){
System.out.println("Set contains apple");
}

//检查集合是否为空
st.isEmpty();

//创建集合的浅拷贝
st.clone();

//将集合转为数组
Object array = st.toArray();

//获取HashSet的大小,使用size()方法获取集合中元素的个数
st.size();

//清空HashSet中的所有元素
st.erase();

//HashSet遍历
//1.使用iterator遍历
Iterator<String> iterator = st.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
//2.使用增强for循环遍历
for(String s : st){
System.out.println(s);
}
}
}

Stack 基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class StackExample{
public static void main(String[] args){
Stack<Integer> st = new Stack<>();

//压入元素
st.push(1);

//移除栈顶的元素并返回该元素
st.pop();

//返回栈顶的元素但不移除它
st.peek();

//判断栈是否为空
st.isEmpty();

//查找元素在栈中的位置
int pos = st.serach(10);
}
}

Deque基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class DequeExample{
public void static main(String[] args){

Deque<Integer> deque = new ArrayDeque<>();
//插入元素(从两端)
deque.addFirst(1); //将1插到队列前端
deque.addLast(2); //将2插到队列后端
deque.offerFirst(3); // 将3插到队列前端,成功返回true
deque.offerLast(4); //将4插到队列后端,成功返回true

//移除元素(从两端);
deque.removeFirst();
deque.removeLast();
int pollfirst = deque.pollFirst(); //移除并返回队首元素
int polllast = deque.pollLast(); //移除并返回队尾元素

//查看元素
int first = deque.getFirst();
int last = deque.getLast();
int peekFirst = deque.peekFirst(); //查看队首元素,如果为空则返回null
int peekLast = deque.peekLast(); //查看队尾元素,如果为空则返回null

int size = deque.size();
boolean isEmpty = deque.isEmpty();
deque.clear();
}
}

常见的转换操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//数组转换为固定大小的列表
String[] arrays = {"a", "b", "c"};
List<String> list = Arrays.asList(arrays);

//数组转换为可变大小的列表
List<String> list = new ArrayList<>(Arrays.asList(arrays));

//列表转换为数组
Object[] array = list.toArray();

//列表转换为String数组
String[] array = list.toArray(new String[0]);
Integer[] integers = integerList.toArray(new Integer[0]);

//Integer列表转换为int数组
List<Integer> list = Arrays.asList(1, 2, 3);
int[] array = list.stream().mapToInt(Integer::intValue).toArray();

List<List<Integer>> res = new ArrayList<>();
int[][] arrays = res.stream()
.map(list->list.stream().mapToInt(Integer::intValue).toArray())
.toArray(int[][]::new);

//int数组转换为List<Integer>
int[] a = new int[]{1, 2, 3};
List<Integer> integers = Arrays.stream(a).boxed().collect(Collectors.toList());

int[][] intArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
List<List<Integer>> list = Arrays.stream(intArray)
.map(row -> Arrays.stream(row).boxed().collect(Collectors.toList()))
.collect(Collectors.toList());

//字符串转化为整数
String s = "123";
int num = Integer.parseInt(s);
Integer num = Integer.valueOf(s);

//整数转换为字符串
int num = 123;
String s = String.valueOf(num);
String s = Integer.toString(num);

//字符串转换为字符数组
String s = "hello";
char[] ch = s.toCharArray();

//字符串数组转化为字符串
String[] array = {"hello", "world"};
String result = String.join("", array);

//数组转换为字符串(用于调试输出)
int[] array = {1, 2, 3};
String result = Arrays.toString(array); // "[1, 2, 3]"

//字符串转为列表
String s = "a, b, c";
List<String> list = Arrays.asList(s.spilt(","));
String[] str = s.split(",");

//字符串转大写、小写
String s = "Hello";
String upper = s.toUpperCase();
String lower = s.toLowerCase();

Sort方法的应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//Comapare、Comparator、CompareTo太多了,难以记忆,这里放几个常用的

//使用Lambda表达式
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
names.sort((s1, s2) -> Integer.compare(s1.length(), s2.length());

//使用方法引用按自然顺序排序
names.sort(String::CompareTo)

String[] arr = {"banana", "apple", "cherry", "date"};
Arrays.sort(arr, (s1, s2)->Integer.compare(s1.length(), s2.length());

//先按长度排序,再按字典序排序
Arrays.sort(arr, (s1, s2)->{
int lengthCompare = Integer.compare(s1.length(), s2.length());
if(lengthCompare != 0){
return lengthComapre;
}else return s1.compareTo(s2);
})

/*
实现comparable
*/
import java.util.*;

class Person implements Comparable<Person> {
String name;
int age;

Person(String name, int age) {
this.name = name;
this.age = age;
}

@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age);
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public class Main {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);

// 使用自然排序(按年龄)
Collections.sort(people);

System.out.println(people); // 输出:[Bob (25), Alice (30), Charlie (35)]
}
}

Java输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.scanner

public class Main{
public static void main(String[] args){

//标准输入输出,nextInt()读取下一个整数
Scanner sc = new Scanner(System.in);

int a = sc.nextInt();
int b = sc.nextInt();

System.out.println(a + b);

//处理多组输入
while(sc.hasNext()){
a = sc.nextInt();
b = sc.nextInt();
System.out.println(a + b);
}

//行输入
while(sc.hasNextLine()){
//读取一行
String line = sc.nextLine();

//将行按空格分割为数据
String[] numbers = line.split(" ");
int sum = 0;

for(String num : numbers){
sum += Integer.parseInt(num);
}
}

//数组 输入
int n = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i ++){
arr[i] = sc.nextInt();
}

}
}
Comments