【JAVA基础】Collections方法的具体使用方法
java基础中Collections
及collect(toList,toSet,toMap)
的用法
package com.gaofeng;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class demo01 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌-男-15","张无忌1-男-15","周芷若-女-20","小昭-女-18","张三丰-男-100","谢逊-男-40");
List<String> collect = list.stream().filter(s -> "男".equals(s.split("-")[1])).collect(Collectors.toList());
System.out.println(collect);
Set<String> collect1 = list.stream().filter(s -> "男".equals(s.split("-")[1])).collect(Collectors.toSet());
System.out.println(collect1);
boolean contains = collect1.contains("张无忌-男-15");
System.out.println(contains);
Map<String, Integer> collect2 = list.stream().filter(s -> "男".equals(s.split("-")[1])).collect(Collectors.toMap(new Function<String, String>() {
@Override
public String apply(String s) {
return s.split("-")[0];
}
}, new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return Integer.parseInt(s.split("-")[2]);
}
}));
System.out.println(collect2);
// 简化写法
Map<String, Integer> collect3 = list.stream().filter(s -> "男".equals(s.split("-")[1])).collect(Collectors.toMap(
s -> s.split("-")[0],
s -> Integer.parseInt(s.split("-")[2])
));
System.out.println(collect3);
}
}
- 算法练习1:
一个集合里面添加任意的数字,然后过滤掉技奇数,保留偶数
public class demo02 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Collections.addAll(list,1,2,3,4,5,6,7,8,9,10);
List<Integer> collect = list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());
System.out.println(collect);
}
}
- 算法练习2:
一个集合里面添加如下的姓名和年龄字符串数据,进行过滤处理
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list,"张三,23","李四,15","刘旺,30");
Map<String, Integer> collect5 = list.stream().filter(s -> Integer.parseInt(s.split(",")[1]) > 24).collect(Collectors.toMap(new Function<String, String>() {
@Override
public String apply(String s) {
return s.split(",")[0];
}
}, new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return Integer.parseInt(s.split(",")[1]);
}
}));
System.out.println(collect5);
Map<String, Integer> collect6 = list.stream().filter(s -> Integer.parseInt(s.split(",")[1]) > 24).collect(Collectors.toMap(s -> s.split(",")[0], s -> Integer.parseInt(s.split(",")[1])
));
System.out.println(collect6);
- 方法引用
public class demo04 {
public static void main(String[] args) {
Integer[] arr = {1,2,3,4,5,6,7,8,9};
// Arrays.sort(arr, new Comparator<Integer>(){
// @Override
// public int compare(Integer o1, Integer o2) {
// return o2 - o1;
// }
// });
// Arrays.sort(arr, (Integer o1, Integer o2) -> {
// return o2 - o1;
// });
// Arrays.sort(arr, (o1, o2) -> o2 - o1);
Arrays.sort(arr, demo04::compare);
System.out.println(Arrays.toString(arr));
}
public static int compare(Integer o1 ,Integer o2 ){
return o2 - o1;
}
}