Map 排序

正序

1
2
3
4
5
6
7
8
private <K extends Comparable, V extends Comparable> Map<K, V> sortMapByValues2(Map<K, V> aMap) {
HashMap<K, V> finalOut = new LinkedHashMap<>();
aMap.entrySet()
.stream()
.sorted((p1, p2) -> p1.getValue().compareTo(p2.getValue()))
.collect(Collectors.toList()).forEach(ele -> finalOut.put(ele.getKey(), ele.getValue()));
return finalOut;
}

倒序

1
2
3
4
5
6
7
8
private <K extends Comparable, V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> aMap) {
HashMap<K, V> finalOut = new LinkedHashMap<>();
aMap.entrySet()
.stream()
.sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
.collect(Collectors.toList()).forEach(ele -> finalOut.put(ele.getKey(), ele.getValue()));
return finalOut;
}

中文字典排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args){
String[] arrays = new String[]{" 北京 ", " 安徽 ", " 海南 ", " 大连 "};
List list = Arrays.asList(arrays);
System.out.println(list.toString());
Collections.sort(list, new TestUtil());
System.out.println(list.toString());
}

public class TestUtil implements Comparator {
public int compare(Object o1, Object o2) {
try {
// 取得比较对象的汉字编码,并将其转换成字符串
String s1 = new String(o1.toString().getBytes("GB2312"), "ISO-8859-1");
String s2 = new String(o2.toString().getBytes("GB2312"), "ISO-8859-1");
// 运用 String 类的 compareTo()方法对两对象进行比较
return s1.compareTo(s2);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}

隐藏手机号码

1
2
3
4
5
6
7
8
int arr[] = new int[]{8,2,1,0,3};
int index[] = new int[]{2,0,3,2,4,0,1,3,2,3,3};
String tel = "";
for (int i: index) {
System.out.println("index:"+index[i]+",i:"+i+",arr[i]:"+arr[i]);
tel += arr[i];
}
System.out.println(" 联系:"+tel);

根据传递的长度,随机分配 60S 内不重复的数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public int[] randomNextMinute(int length) {
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
int ran;
while (true) {
ran = (int) (Math.random() * 60);
if (ran > 60) {
ran = ran - 60;
}
boolean tag = false;
for (int j = 0; j < arr.length; j++) {
if (arr[j] == ran) {
tag = true;
}
}
if (!tag) {
break;
}
}
arr[i] = ran;
}
return arr;
}

javascript 循环生成 10 个不重复的随机数

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
$(function() {
var arr = new Array(10);
function getrand() {
for (var i = 0; i < arr.length; i++) {
var ran = 0;
while (true) {
ran = Math.floor(Math.random() * 10);
//alert(ran);
var tag = false;
for (var j = 0; j < arr.length; j++) {
if (arr[j] == ran) {
tag = true;
}
}
if (tag == false) {
break;
}
}
arr[i] = ran;
//alert("ran:" + ran);
//alert("arr:" + arr);
}
return arr;
}
var count = 0;
var ranarr = getrand();
$("input[name=btn]").bind("click",function(){
for(var i =count;i<ranarr.length;i++){
if(ranarr[count] == 0){
ranarr[count] = 10;
}
$("p").text(ranarr[count]);
}
count++;
});
});