引出
用来存储多个元素,是一个容器;
List可以使用lamda表达式;
一、数组
String[] users=new String[0];
1.新增元素
先扩大数组的大小,然后放元素
findStu = Arrays.copyOf(findStu, findStu.length+1);
findStu[findStu.length-1] = stuList[i];
2.删除元素
根据id删除学生的信息
下面的思路是:
1)找到要删除的学生,把数组的最后一个赋值到该位置,然后把最后一个删除,弊端是顺序改变;
//根据id删除学生信息
public Stu[] delete(int id,Stu[] stuList) {
for (int i = 0; i < stuList.length; i++) {
if (id == stuList[i].id) {
stuList[i] = stuList[stuList.length-1];
break;
}
}
stuList = Arrays.copyOf(stuList, stuList.length-1);
return stuList;
}
2)创建一个新的数组,将需要保留的元素复制到新数组中,然后将新数组赋值给原数组。弊端是需要新的数字,并且要遍历
public Stu[] delete(int id,Stu[] stuList) {
Stu[] newList = new Stu[stuList.length - 1]; // 新的数组
int j = 0; // 新数组的索引
for (int i = 0; i < stuList.length; i++) {
if (id != stuList[i].id) {
newList[j] = stuList[i];
j++;
}
}
return newList;
}
二、集合List
集合的底层数组,List提供了快捷的方法进行操作
1.常用方法,增删取
ArrayList adminList = new ArrayList(); //用list保存员工信息
1)add
adminList.add(admin)
2)get(下标)
adminList.get(i)
3)remove()
adminList.remove(i); // 根据索引删除
4)clear()
清除元素
System.out.println(5>3 || 10/0 > 4);
2.ArrayList和LinkedList
- ArrayList 空间是连续的,List的内容需要一个挨着一个;
- LinkedList 存储空间不需要连续,需要有指向,指向下一个元素
3.forEach方法
list.forEach(System.out::println);
三、List的扩展
1.深入理解List【重要】
List接口>>>Collection接口(定义了add等方法)>>>Iterbale(iterator()迭代器)
- 是一个动态数组 :transient Object[] elementData;
- 数组的默认长度为10:private static final int DEFAULT_CAPACITY = 10;
- 扩容方案,原长度的1.5倍:int newCapacity = oldCapacity + (oldCapacity >> 1);
- 初始化较大的空间,防止重复扩容:list = new ArrayList<>(100);
2.删除元素的问题【重要】
- 用索引删除会出现问题
- 用迭代器的特性删除Iterator it = list.iterator();
// 初始化一个100大小的List,随机放1-100的数字,删除能被2,3,5整除的数
List<Integer> list = new ArrayList<>(100);
for(int i=1;i<=100;i++){
list.add(i);
}
Iterator<Integer> it = list.iterator();
while (it.hasNext()){ //判断有没有下一个元素
int t = it.next(); //拿出下一个元素
if(t%2==0|| t%3==0||t%5==0){
it.remove();
}
}
System.out.println(list);
四、list.remove(对象)
- 需要对象实现equals()方法;可选实现hashCode()方法,用来快速定位对象
1.类实现equals和hashCode方法
equals方法必须,hashCode非必须;
只需要比较older类里的id或者identity,如果任一相等就能删除
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Older older = (Older) o;
return Objects.equals(id, older.id) || Objects.equals(identity, older.identity); // id相等或者identity相等就能删
}
@Override
public int hashCode() {
return Objects.hash(id, identity);
}
方法的实现
@Override
public void deleteById(String id) {
// id 为null 和 ""
if (Objects.isNull(id) || "".equals(id)) {
System.out.println("401异常,id为空...");
return;
}
Older newOlder = new Older();
newOlder.setId(id); // 只要ID相等就能删除,取决于上面类里面的equals方法
boolean removeFlag = list.remove(newOlder); // 根据对象删除,返回True和false
if (!removeFlag) {
System.out.println("402异常,未找到该对象,删除失败...");
} else {
System.out.println("成功删除编号为" + id + "的老人信息");
}
}
五、函数式编程—lamda表达式
@FunctionalInterface
List<Older> ageList = list.stream() // 流对象
.filter(older -> (30 < older.getAge() && older.getAge() < 80)) // 过滤条件
.collect(Collectors.toList()); // 回收结果
1.排序
int格式排序
List<Older> sortByAge = list.stream()
.sorted((o1, o2) -> o2.getAge() - o1.getAge()) // 降序
.collect(Collectors.toList());
BigDecimal排序
List<Food> sorted = list.stream()
.sorted((o1, o2) -> o1.getPrice().compareTo(o2.getPrice())) // 升序
.collect(Collectors.toList());
Date类型排序
List<Food> sorted = list.stream()
.sorted((o1, o2) -> o1.getProductionDate().compareTo(o2.getProductionDate()))
.collect(Collectors.toList());
Collections.sort(list, (o1, o2) -> o1.getProductionDate().compareTo(o2.getProductionDate()));
2.limit:限制数量
需求:找出年龄最低的5个
List<Older> limitTwo2 = list.stream()
.sorted((o1, o2) -> o2.getAge()-o1.getAge())
.limit(2) // 放在排序后面,限制数量
.collect(Collectors.toList());
List<Older> sortByAge = list.stream()
.sorted((o1, o2) -> o2.getAge() - o1.getAge())
.collect(Collectors.toList());
System.out.println("找出年龄最大的2个人"); // subList 方法
System.out.println(sortByAge.subList(0, 2));
3.最大最小
需要用get()获取
System.out.println("最大值"+
list.stream()
.max((o1, o2) -> o1.getAge()-o2.getAge())
.get()); // 需要用get()方法回收
4.filter:过滤
找到所有的偶数
List<Integer> numbers = Arrays.asList(1,2,3,4,5,9,6,43,3);
List<Integer> newNum = numbers.stream()
.filter(integer -> integer % 2 == 0)
.collect(Collectors.toList());
System.out.println(newNum);
5.distinct:去重
StringBuilder去重
List<StringBuilder> allChildJob = list.stream()
.map(o -> o.getChildJob()) // map 获得某个属性值
.collect(Collectors.toList());
List<String> result = allChildJob.stream()
.map(StringBuilder::toString) // map 将StringBuilder变成String
.distinct() // 进行去重
.collect(Collectors.toList());
6.求和
int类型求和
// 把所有年龄找出来求和,计算平均值
System.out.println(list.stream()
.mapToInt(older->older.getAge()) // 获取年龄
.sum());
BigDecimal求和
list.stream()
.map(older -> older.getSal())
.reduce(BigDecimal.ZERO,BigDecimal::add) // 用reduce求和
7.综合应用
模糊查询
- 模糊查询名字、简介中含有的某个输入信息,如输入“玫瑰”,查找出名字或简介中含有“玫瑰”的美食。
@Override
public List<Food> findKeywordInNameDesc(String keyWord) {
List<Food> find = list.stream()
.filter(food -> food.getName().contains(keyWord) || food.getDesc().indexOf(keyWord)!=-1) // 这里的food.getDesc()获得是StringBuilder
.collect(Collectors.toList());
return find;
}
综合查询
- 综合查询输入工厂,味道,成分,价格在某个范围之内的美食。
// 取交集
System.out.println("综合查询,工厂,味道,成分,价格");
List<Food> intersection = new ArrayList<>(findFactory);
intersection.retainAll(findPrice);
intersection.retainAll(findIngredient);
intersection.retainAll(findTaste);
// 根据工厂名查询
List<Food> find = list.stream().filter(food -> food.getFactory().equals(factory)).collect(Collectors.toList());
// BigDecimal类型的查询
@Override
public List<Food> findByPrice(String max, String min) {
// 查询价格在某个区间的美食
// max,min为null或空异常
if (Objects.isNull(max) || Objects.isNull(min) || "".equals(max) || "".equals(min)){
throw new NullOrNoInputException("401异常,输入max或min为空");
}
// max小于min异常
if((new BigDecimal(min)).compareTo(new BigDecimal(max))>0){
throw new ErrorInputException("402异常,输入的max比min小");
}
List<Food> find = list.stream()
.filter(food -> food.getPrice().compareTo(new BigDecimal(min))>0
&& food.getPrice().compareTo(new BigDecimal(max))<0)
.collect(Collectors.toList());
return find;
}
总结
1.list的迭代器属性,iterator,应用于安全删除元素;
2.list的remove对象方法,需要对象实现equals方法;
3.List使用lamda表达式;
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/165174.html