Java集合容器面试题(2020最新版)
public class showMessage {
public static void main(String[] args) {
PG pg1 = new PG(01, 24, "张三", 10000.0, 85);
Employee pg2 = new PG(02, 26, "李四", 12000.0, 95);
Employee pm1 = new PM(1001, 45, "tom", 70000.0, 90);
Employee pm2 = new PM(1002, 37, "jim", 65000.0, 87);
List<? super Employee> list = new ArrayList<>();
list.add(pg1);
list.add(pg2);
list.add(pm1);
list.add(pm2);
// 普通for
for (int i = 0; i < list.size(); i++) {
Employee employee = (Employee)list.get(i);
employee.show();
}
// lamda
list.forEach(emp -> {
Employee emp1 = (Employee) emp;
emp1.show();
});
//迭代器
ListIterator<? super Employee> listIterator = list.listIterator();
while (listIterator.hasNext()) {
Employee employee = (Employee)listIterator.next();
employee.show();
}
// 增强for
for (Object o : list) {
Employee o1 = (Employee) o;
o1.show();
}
}
}
public class ShowMessage {
public static void main(String[] args) {
Map<Integer,Employee> map = new HashMap<>(4);
PG pg1 = new PG(01, 24, "张三", 10000.0, 85);
Employee pg2 = new PG(02, 26, "李四", 12000.0, 95);
Employee pm1 = new PM(1001, 45, "tom", 70000.0, 90);
Employee pm2 = new PM(1002, 37, "jim", 65000.0, 87);
map.put(pg1.getId(), pg1);
map.put(pg2.getId(), pg2);
map.put(pm1.getId(), pm1);
map.put(pm2.getId(), pm2);
//entrySet
for (Map.Entry<Integer, Employee> key : map.entrySet()) {
key.getValue().show();
}
//keySet
for (Integer key : map.keySet()) {
map.get(key).show();
}
}
}
public class User implements Comparable<User>{
private Integer id;
private String name;
private Integer age;
/**
* 自定排序的规则
* 1.根据用户年龄 升序排列
* 2.年龄一致的时候 利用id进行升序排列
* @param user
* @return
*/
@Override
public int compareTo(User user) {
Objects.requireNonNull(user);
if(this==user){
return 0;
}
int result = this.age.compareTo(user.age);
if(result==0){
result = this.id.compareTo(user.id);
}
return result;//int;
}
}
Collections.sort(userList,(user1,user2)->{
int result = user2.getAge().compareTo(user1.getAge());
if(result == 0){
result = user2.getId().compareTo(user1.getId());
}
return result;
});
private static void demo2() {
//去除重复数据
List<Integer> num = new ArrayList<>();
Collections.addAll(num, 1, 10, 1, 2, 3, 3, 2);
// 去重
List<Integer> collect = num.stream().distinct().collect(Collectors.toList());
}
private static void demo1() {
//删除名字里面包含m的元素
List<User> userList = new ArrayList<>(10);
Collections.addAll(userList,
new User(1, "jim", 20),
new User(3, "tom", 18),
new User(2, "lily", 18),
new User(5, "zhangsan", 18),
new User(5, "zhm", 18),
new User(4, "kim", 18));
//第一种方式
userList.removeIf((user -> user.getName().contains("m")));
//第二种方式:获得并行化流
Stream<User> userStream = userList.parallelStream();// list集合的所有的元素都在userStream里面
userStream = userStream.filter(user -> !user.getName().contains("m"));//userStream只有不包含m的对象
List<User> collect = userStream.collect(Collectors.toList());
//简写(推荐)
List<User> collect = userList.parallelStream().filter(user -> !user.getName().contains("m")).collect(Collectors.toList());
}