一些面试算法中的Java基本操作运算
很久没有真的写程序,一些基本的Utils的使用也淡忘了。这里总结一下:
数组
数组转化成List
//Convert a two dimension to a List. Array is an object in Java. So we can do it.
List<int[]> a = Arrays.asList(intervals);
// One dimension
// https://www.techiedelight.com/convert-int-array-list-integer/
int[] bb= {1,3,4,5};
List<Integer> ddd = Arrays.stream(bb).boxed().collect(Collectors.toList());
//Or we can just use Integer array:
Integer[] cc = {1,3,4,5};
List<Integer> rrr = Arrays.asList( cc );
List转化为数组
new ArrayList<>().toArray(new String[length]);
//Two dimension array. List of an array
List<int[]> list;//[[1,2],[3,5]]
list.toArray(new int[list.size()][]);
排序数组
//Sort a two dimension array by the first element in each array ite.
// [[1,2],[5,6],[3,4]]. --> [[1,2],[3,4],[5,6]
Arrays.sort(intervals, (a,b) -> Integer.compare(a[0],b[0]));
排序List
Collections.sort(list);
打印一维数组
//唯一不好打印的就是数组,List和Map都可以直接打印
System.out.println(Arrays.toString({1,3,4,5});
打印多于一维数组
int[][] abc = {{1,2},{2,5},{5,9};
System.out.println(Arrays.deepToString(abc}; //字面量不能直接使用. And please note that the deepToString cannot be used to an array.
打印List
list.forEach(System.out::println);
//Actually 'list' can be print directly. The format is [d,w]
答应list里面含有array
list.forEach( (item) -> System.out.println(Arrays.toString(item)));
MAP
Merge
//Adding 1 for the key
map.merge("key", 1, (old, new1) -> old + new1);
//Sum
map.merge("key", 3, Integer::sum);
Print a map
// Actually map can be print directly. the format {a=b,a2=b3}
map.forEach( (key,value) -> System.out.println("key:" + key + "value:"+value));
map.keySet().forEach( (key) -> XXX );
map.values().forEACH( (value) -> XXX);
其他
Objects.requireNotNull(param);
boolean的值只能是true,false,而不能是0,1.
char是用单引号: char abc=’a’;