Java基础(2)——数组[] & 集合List,函数式编程Lamda表达式

Java基础(2)——数组[] & 集合List,函数式编程Lamda表达式_第1张图片

目录

  • 引出
  • 一、数组
    • 1.新增元素
    • 2.删除元素
    • 3.二维数组
  • 二、集合List
    • 1.常用方法,增删取
    • 2.ArrayList和LinkedList
    • 3.forEach方法
  • 三、List的扩展
    • 1.深入理解List【重要】
    • 2.删除元素的问题【重要】
  • 四、list.remove(对象)
    • 1.类实现equals和hashCode方法
  • 五、函数式编程—lamda表达式
    • 1.排序
      • int格式排序
      • BigDecimal排序
      • Date类型排序
    • 2.limit:限制数量
    • 3.最大最小
    • 4.filter:过滤
    • 5.distinct:去重
      • StringBuilder去重
    • 6.求和
      • int类型求和
      • BigDecimal求和
    • 7.综合应用
      • 模糊查询
      • 综合查询
  • 总结

引出

用来存储多个元素,是一个容器;
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;
}

3.二维数组

假设现在有3个班的学生成绩,使用一个数组该怎么存储(数据打包)?

int[] class1 = {100 , 98 , 97};

int[] class2 = {99 , 98 , 76};

int[] class3 = {87 , 99 , 100};

Java基础(2)——数组[] & 集合List,函数式编程Lamda表达式_第2张图片

public class Test3 {
    public static void main(String[] args) {
        int a = 90;
        int b = 98;
        int c = 99;
        /* 用数组存放多个值 */
        // 一维数组
        int[] scores = {90 , 98 , 99};
        int[] scores2 = {a , b , c};
        // **********************************二维数组的基本概念和定义********************************************************************
        //  4、假设现在有3个班的学生成绩,使用一个数组该怎么存储(数据打包)?
        int[] class1 = {95,99,100};
        int[] class2 = {96,97,100};
        int[] class3 = {99,60,100};
        // 二维数组 - > 数组元素又是一个数组!
        // 三种写法:
        int[][] classz = { {95,99,100} , {96,97,100} , {99,60,100} };
        // int[][] clazz2 = {class1 ,class2 , class3 };
        int[][] clazz3 = new int[3][3]; // 3行3列  -》 场景 3个班级 , 每个班3个
        // 第二行第二列: 97
        System.out.println(classz[1][1]);
//        代码: 第三行第三列: 数组名[2][2]
        System.out.println(classz[2][2]);
        System.out.println(classz[classz.length - 1][2]);
        // ********************************************二维数组的应用**********************************************************
        //        使用循环遍历二维数组
        for (int i = 0; i < classz.length; i++) {
             int[] scroes = classz[i];  // 从某个班取出该班所有的学生成绩
            for (int j = 0; j < scroes.length; j++) {
                System.out.print(scroes[j] + "\t");
            }
            System.out.println();
        }
        System.out.println("------------------写法二");
        for (int i = 0; i < classz.length; i++) {
            for (int j = 0; j < classz[i].length; j++) {
                System.out.print(classz[i][j] + "\t");
            }
            System.out.println();
        }
        // 三维 ...  ......
        int[][][] aaa;
        int[][][][] bb;
        int[][][][][][][][][][] ccc = new int[5][5][5][5][5][5][5][5][5][5];
    }
}

二、集合List

集合的底层数组,List提供了快捷的方法进行操作

Java基础(2)——数组[] & 集合List,函数式编程Lamda表达式_第3张图片

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);

Java基础(2)——数组[] & 集合List,函数式编程Lamda表达式_第4张图片

三、List的扩展

1.深入理解List【重要】

Java基础(2)——数组[] & 集合List,函数式编程Lamda表达式_第5张图片

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表达式

Java基础(2)——数组[] & 集合List,函数式编程Lamda表达式_第6张图片

@FunctionalInterface

出现在接口,则此接口可以使用lamda表达式
Java基础(2)——数组[] & 集合List,函数式编程Lamda表达式_第7张图片
表达式示例:

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 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表达式;

你可能感兴趣的:(Java,java,学习,list)