import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型一维数组
*/
public int[] FindNumsAppearOnce (int[] nums) {
// write code here
int[] res = new int[2];
if(nums == null || nums.length == 0)
return res;
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
map.merge(nums[i], 1, Integer::sum);
}
res = map.entrySet().stream()
.filter(e -> e.getValue() == 1)
.mapToInt(Map.Entry::getKey)
.toArray();
return res;
}
}
map.entrySet().stream()
:
map
是一个Map
对象,这里没有显示其类型,但它实现了java.util.Map
接口。entrySet()
方法返回map
中所有键值对的集合视图,这个集合的元素是Map.Entry
类型。stream()
方法将这个集合转换成一个流(Stream
),允许你以声明式方式处理这个集合。
.filter(e -> e.getValue() == 1)
:
filter
是一个中间操作,它接受一个Predicate
(在这里是一个lambda表达式e -> e.getValue() == 1
)。- 这个
Predicate
检查每个Map.Entry
对象的值(e.getValue()
)是否等于1。 filter
方法会生成一个新的流,只包含满足条件(值等于1)的元素。
.mapToInt(Map.Entry::getKey)
:
mapToInt
是一个中间操作,它将流中的每个元素(在这里是Map.Entry
对象)映射到一个int
类型的值。Map.Entry::getKey
是一个方法引用,它获取Map.Entry
对象的键,这里假设键是int
类型。mapToInt
方法返回一个IntStream
,这是一个专门处理int
类型元素的流。类似的还有mapToDouble、mapToLong、mapToInt
.toArray()
:
toArray
是一个终端操作,它将流中的元素收集到一个数组中。- 对于
IntStream
,toArray
方法返回一个int[]
数组。 - 这个操作会触发流的遍历,并收集所有元素到一个数组中。
import java.util.Map;
import java.util.stream.Collectors;
Map<String, Integer> map = ... // 假设这是你的Map
String[] keysArray = map.keySet().stream()
.collect(Collectors.toList())
.toArray(new String[0]);
步骤解释
map.keySet().stream()
:获取Map
中所有键的集合,并将其转换为一个流(Stream
)。.collect(Collectors.toList())
:使用Collectors.toList()
收集器将流中的元素收集到一个List
中。.toArray(new String[0])
:将List
转换为一个String
数组。传递给toArray
方法的new String[0]
是一个空的String
数组,用于指示返回数组的类型。