JAVA基础:集合 (习题笔记)

写完一定记得 Ctrl+Alt+L 让代码格式标准

1.使用List和Map存放多个图书信息,遍历并输出。其中商品属性:编号,名称,单价,出版社;使用商品编号作为Map中的key。

Books类

java 复制代码
package set.saturdayPlan;

public class Books {
    private Integer id;//编号
    private String name;//名称
    private Double price;//价格
    private String publishingHouse;//出版社

    //无参构造
    public Books() {
    }

    //有参构造
    public Books(Integer id, String name, Double price, String publishingHouse) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.publishingHouse = publishingHouse;
    }

    //get , set 方法
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getPublishingHouse() {
        return publishingHouse;
    }

    public void setPublishingHouse(String publishingHouse) {
        this.publishingHouse = publishingHouse;
    }

    //重写toString
    @Override
    public String toString() {
        return "Books{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", publishingHouse='" + publishingHouse + '\'' +
                '}';
    }

}

List

java 复制代码
package set.saturdayPlan;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BooksTextList {
    //程序入口
    public static void main(String[] args) {
        //创建List集合对象
        List<Books> books = new ArrayList<>();
        //添加图书信息
        books.add(new Books(123, "西游记", 60.5, "清华出版社"));
        books.add(new Books(124, "红楼梦", 70.5, "北京出版社"));
        books.add(new Books(126, "水浒传", 70.2, "南京出版社"));
        books.add(new Books(125, "三国演义", 80.9, "山东出版社"));
        //遍历List
        System.out.println("===============================================================");
        //方法一 for
        for (int i = 0; i < books.size(); i++) {
            System.out.println(books.get(i));
        }
        System.out.println("===============================================================");
        //方法二 增强for
        for (Books book : books) {
            System.out.println(book);
        }
        System.out.println("===============================================================");
        //方法三 迭代器
        Iterator<Books> iterator = books.iterator();
        while (iterator.hasNext()) {
            Books books1 = iterator.next();
            System.out.println(books1);
        }


    }
}

正常写一个遍历就可以。
*

Map

直接使用Map
java 复制代码
package set.saturdayPlan;

import java.util.*;

public class BooksTextMap {
    //程序入口
    public static void main(String[] args) {
        //创建Map集合对象
        Map<Integer, Books> map = new TreeMap<>();
        //输入图书信息
        Books boo1 = new Books(123, "西游记", 60.5, "清华出版社");
        Books boo2 = new Books(124, "红楼梦", 70.5, "北京出版社");
        Books boo3 = new Books(126, "水浒传", 70.2, "南京出版社");
        Books boo4 = new Books(125, "三国演义", 80.9, "山东出版社");
        //存储到Map集合 使用商品编号作为Map中的key
        map.put(boo1.getId(), boo1);
        map.put(boo2.getId(), boo2);
        map.put(boo3.getId(), boo3);
        map.put(boo4.getId(), boo4);
        //遍历Map
        System.out.println("=======================================================================");
        //方法一 keySet() 增强for
        Set<Integer> set = map.keySet();
        for (Integer integer : set) {
            System.out.println(map.get(integer));
        }
        System.out.println("=======================================================================");
        //方法二 keySet() 迭代器
        Iterator<Integer> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            Integer integer = iterator.next();
            System.out.println(map.get(integer));
        }
        System.out.println("=======================================================================");
        //方法三 values() 增强for
        Collection<Books> values = map.values();
        for (Books value : values) {
            System.out.println(value);
        }
        System.out.println("=======================================================================");
        //方法四 values() 迭代器
        Iterator<Books> iterator1 = map.values().iterator();
        while (iterator1.hasNext()) {
            Books value = iterator1.next();
            System.out.println(value);
        }
        System.out.println("=======================================================================");
        //方法五 entrySet() 增强for
        Set<Map.Entry<Integer, Books>> entries = map.entrySet();
        for (Map.Entry<Integer, Books> entry : entries) {
            System.out.println(entry.getValue());
        }
        System.out.println("=======================================================================");
        //方法六 迭代器
        Iterator<Map.Entry<Integer, Books>> iterator2 = map.entrySet().iterator();
        while (iterator2.hasNext()) {
            Map.Entry<Integer, Books> entry = iterator2.next();
            System.out.println(entry.getValue());
        }

    }
}

正常写一个遍历就可以。
2.

LIst To Map
java 复制代码
//List To Map
        Map<Integer, Books> map = new TreeMap<>();
        Iterator<Books> iterator1 = books.iterator();
        while (iterator1.hasNext()) {
            Books books1 = iterator1.next();
            map.put(books1.getId(), books1);//使用商品编号作为Map中的key
        }
        //遍历Map
        System.out.println("==================================================================");
        //方法一  keySet()增强for
        Set<Integer> set = map.keySet();
        for (Integer integer : set) {
            System.out.println(map.get(integer));
        }
        System.out.println("==================================================================");
        //方法二 keySet()迭代器
        Iterator<Integer> iterator2 = map.keySet().iterator();
        while (iterator2.hasNext()) {
            Integer ks2 = iterator2.next();
            System.out.println(map.get(ks2));
        }
        System.out.println("==================================================================");
        //方法三 values()增强for
        Collection<Books> values = map.values();
        for (Books value : values) {
            System.out.println(value);
        }
        System.out.println("==================================================================");
        //方法四 values()迭代器
        Iterator<Books> iterator3 = map.values().iterator();
        while (iterator3.hasNext()) {
            Books value2 = iterator3.next();
            System.out.println(value2);
        }
        System.out.println("==================================================================");
        //方法五 entrySet()增强for
        Set<Map.Entry<Integer, Books>> entries = map.entrySet();
        for (Map.Entry<Integer, Books> entry : entries) {
            System.out.println(entry.getValue());
        }
        System.out.println("==================================================================");
        //方法六 entrySet()迭代器
        Iterator<Map.Entry<Integer, Books>> iterator4 = map.entrySet().iterator();
        while (iterator4.hasNext()) {
            Map.Entry<Integer, Books> entry2 = iterator4.next();
            System.out.println(entry2.getValue());
        }

在List类的基础上,不对List集合进行遍历,将List集合中的存储到Map集合中,对Map集合进行遍历,正常写一个遍历就可以。

2.使用HashSet和TreeSet存储多个商品信息,遍历并输出;其中商品属性:编号,名称,单价,出版社;要求向其中添加多个相同的商品,验证集合中元素的唯一性。

提示:向HashSet中添加自定义类的对象信息,需要重写hashCode和equals( )

向TreeSet中添加自定义类的对象信息,需要实现Comparable接口,指定比较规则

HashSet----Books类

java 复制代码
  //重写equals()和hashCode()

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Books books = (Books) o;
        return Objects.equals(id, books.id) && Objects.equals(name, books.name) && Objects.equals(price, books.price) && Objects.equals(publishingHouse, books.publishingHouse);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, price, publishingHouse);
    }

与上一题所需属性相同,沿用上一题的Books类进行修改,重写hashCode和equals( )
*

HashSet

java 复制代码
package set.saturdayPlan;

import com.jr.demo1.Book;

import java.util.*;

public class BooksTextHashSet {
    //程序入口
    public static void main(String[] args) {
        //创建HashSet集合对象
        HashSet<Books> books = new HashSet<>();
        //输入商品信息
        books.add(new Books(123, "西游记", 60.5, "清华出版社"));
        books.add(new Books(124, "红楼梦", 70.5, "北京出版社"));
        books.add(new Books(126, "水浒传", 70.2, "南京出版社"));
        books.add(new Books(125, "三国演义", 80.9, "山东出版社"));
        //遍历Set
        //方法一 增强for
        for (Books book : books) {
            System.out.println(book);
        }
        System.out.println("=================================================================");
        //方法二 迭代器
        Iterator<Books> iterator = books.iterator();
        while (iterator.hasNext()) {
            Books books1 = iterator.next();
            System.out.println(books1);
        }

    }
}

正常写一个遍历就可以。
*

TreeSet----Books类 【方法一】

java 复制代码
  //内部比较器

    @Override
    public int compareTo(Books o) {
        return this.id-o.id;//根据编号排序
    }

与上一题所需属性相同,沿用上一题的Books类进行修改,重写内部比较器comparaTo方法,调用内部比较器Comparable接口。
*

TreeSet 【方法一】

java 复制代码
package set.saturdayPlan;

import java.util.*;

public class BooksTextTreeSet {
    //程序入口
    public static void main(String[] args) {
        //创建TreeSet集合对象
        TreeSet<Books> books = new TreeSet<>();
        //输入商品信息
        books.add(new Books(123, "西游记", 60.5, "清华出版社"));
        books.add(new Books(124, "红楼梦", 70.5, "北京出版社"));
        books.add(new Books(126, "水浒传", 70.2, "南京出版社"));
        books.add(new Books(125, "三国演义", 80.9, "山东出版社"));
        //遍历Set
        //方法一 增强for
        for (Books book : books) {
            System.out.println(book);
        }
        System.out.println("=================================================================");
        //方法二 迭代器
        Iterator<Books> iterator = books.iterator();
        while (iterator.hasNext()) {
            Books books1 = iterator.next();
            System.out.println(books1);
        }

    }
}

TreeSet----Books类 【方法二】

沿用上一题Books类,不需要做任何改变。

TreeSet----外部比较器Comparator 【方法二】

java 复制代码
package set.saturdayPlan;

import java.util.Comparator;

public class BooksComparator implements Comparator<Books> {
    //方法重写
    @Override
    public int compare(Books o1, Books o2) {
        /* return o1.getId()-o2.getId();*/  //更简单
        if (o1.getId().equals(o2.getId())) {  //更严谨
            return 0;
        } else {
            return o1.getId() - o2.getId();
        }
    }
}

TreeSet 【方法二】

java 复制代码
 //创建TreeSet集合对象
 TreeSet<Books> books = new TreeSet<>(new BooksComparator());//外部比较器

与方法一TreeSet相同,只在创建集合对象时,加入外部比较器Comparator。

3.实现List和Map数据的转换。具体要求如下:

功能1:定义方法public void listToMap( )将List中Student元素封装到Map中

  1. 使用构造方法Student(int id,String name,int age,String sex )创建多个学生信息并加入List

  2. 遍历List,输出每个Student信息

  3. 遍历Map,输出每个Entry的key和value

  4. 将List中数据放入Map,使用Student的id属性作为key,使用Student对象信息作为value

(1)StudentLTM类
java 复制代码
package set.listToMap;

public class StudentLTM {
   
    private Integer id;
    private String name;
    private Integer age;
    private String sex;

    //构造方法
    public StudentLTM() {
    }

    public StudentLTM(Integer id, String name, Integer age, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    //get  set

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
    //重写toString

    @Override
    public String toString() {
        return "StudentLTM{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}
(2) FunctionOne类
java 复制代码
package set.listToMap;

import com.sun.javafx.binding.ListExpressionHelper;
import set.homework.Student;

import java.util.*;

public class FunctionOne {

    //程序入口
    public static void main(String[] args) {
        //创建对象
        FunctionOne functionOne = new FunctionOne();
        //调用方法
        functionOne.listToMap();
    }

    public void listToMap() {
        //创建集合对象
        List<StudentLTM> list = new ArrayList<>();
        //创建学生信息并加入List
        list.add(new StudentLTM(10, "莉莉", 23, "女"));
        list.add(new StudentLTM(12, "等等", 21, "男"));
        list.add(new StudentLTM(16, "娜娜", 35, "女"));
        list.add(new StudentLTM(11, "威威", 42, "男"));
        //遍历List,输出每个学生的信息  增强for
        for (StudentLTM studentLTM : list) {
            System.out.println(studentLTM);
        }
        //创建Map集合对象
        Map<Integer, StudentLTM> map = new TreeMap<>();
        //将List中数据放入Map,使用Student的id属性作为key,使用Student对象信息作为value
        Iterator<StudentLTM> iterator = list.iterator();
        while (iterator.hasNext()) {
            StudentLTM ltm = iterator.next();
            map.put(ltm.getId(), ltm);
        }
        //遍历Map,输出每个Entry的key和value
        //方法一,entrySet() 迭代器
        System.out.println("=================================================");
        Iterator<Map.Entry<Integer, StudentLTM>> iterator1 = map.entrySet().iterator();
        while (iterator1.hasNext()) {
            Map.Entry<Integer, StudentLTM> entry = iterator1.next();
            System.out.println(entry.getKey() + "---" + entry.getValue());
        }
        System.out.println("===============================================");
        //方法二,entrySet() 增强for
        Set<Map.Entry<Integer, StudentLTM>> entries = map.entrySet();
        for (Map.Entry<Integer, StudentLTM> entry : entries) {
            System.out.println(entry.getKey() + "---" + entry.getValue());
        }

    }
}

正常写一个遍历就可以。

功能2:定义方法public void mapToList( )将Map中Value值Student信息封装到 List

  1. 创建实体类StudentEntry,可以存储Map中每个Entry的信息

  2. 使用构造方法Student(int id,String name,int age,String sex )创建多个学生信息,并使用Student的id属性作为key,存入Map

  3. 创建List对象,每个元素类型是StudentEntry

  4. 将Map中每个Entry信息放入List对象

(1) StudentLTM类

与功能1相同

(2) StudentEntryLTM类
java 复制代码
package set.listToMap;

public class StudentEntryMTL {
    private Integer key;
    private StudentLTM stu;
    //构造方法

    public StudentEntryMTL() {
    }

    public StudentEntryMTL(Integer key, StudentLTM stu) {
        this.key = key;
        this.stu = stu;
    }
    //setter and getter

    public Integer getKey() {
        return key;
    }

    public void setKey(Integer key) {
        this.key = key;
    }

    public StudentLTM getStu() {
        return stu;
    }

    public void setStu(StudentLTM stu) {
        this.stu = stu;
    }

    @Override
    public String toString() {
        return "StudentEntryMTL{" +
                "key=" + key +
                ", stu=" + stu +
                '}';
    }
}
(2) FunctionTwo类
java 复制代码
package set.listToMap;

import java.util.*;

public class FuntionTwo {
  
    //程序入口
    public static void main(String[] args) {
        //创建集合对象
        Map<Integer, StudentLTM> map = new TreeMap<Integer, StudentLTM>();
        //创建多个学生信息,并使用Student的id属性作为key,存入Map
        StudentLTM stu1 = new StudentLTM(10, "莉莉", 23, "女");
        StudentLTM stu2 = new StudentLTM(12, "等等", 21, "男");
        StudentLTM stu3 = new StudentLTM(16, "娜娜", 35, "女");
        StudentLTM stu4 = new StudentLTM(11, "威威", 42, "男");
        //使用Student的id属性作为key,存入Map
        map.put(stu1.getId(), stu1);
        map.put(stu2.getId(), stu2);
        map.put(stu3.getId(), stu3);
        map.put(stu4.getId(), stu4);
        //创建List对象
        List<StudentEntryMTL> list = new ArrayList<>();
        //将Map中每个Entry信息放入List对象
        for (Map.Entry<Integer, StudentLTM> ise : map.entrySet()) {
            StudentEntryMTL stu = new StudentEntryMTL();
            stu.setKey(ise.getKey());
            stu.setStu(ise.getValue());
            list.add(stu);
        }
        //遍历list
        //方法一
        for (StudentEntryMTL student : list) {
            System.out.println(student);
        }
        System.out.println("======================================================");
        //方法二
        Iterator<StudentEntryMTL> iterator = list.iterator();
        while (iterator.hasNext()) {
            StudentEntryMTL ss = iterator.next();
            System.out.println(ss);
        }
        System.out.println("======================================================");
        //方法三
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

    }
}

正常写一个遍历就可以。

功能3:说明Comparable接口的作用,并通过分数来对学生进行排序。

实现Comparable接口的类需要实现compareTo方法,根据该方法可以根据具体的排序规则对容器中的对象进行排序。

java 复制代码
@Override
    public int compareTo(Books o) {
        return this.score-o.score;//根据学生成绩排序
    }

在StudentLTM类中,增加属性--分数score,【增加完--记得对构造方法,Getter and Seetter 以及toString方法进行修】对上面的代码的compareTo方法进行重写即可。

相关推荐
RisunJan2 分钟前
【行测】类比推理-自称他称全同
学习
武子康17 分钟前
Java-193 Spymemcached 深入解析:线程模型、Sharding 与序列化实践全拆解
java·开发语言·redis·缓存·系统架构·memcached·guava
wan55cn@126.com20 分钟前
人类文明可通过技术手段(如加强航天器防护、改进电网设计)缓解地球两极反转带来的影响
人工智能·笔记·搜索引擎·百度·微信
石像鬼₧魂石27 分钟前
Termux ↔ Windows 靶机 反向连接实操命令清单
linux·windows·学习
非凡ghost27 分钟前
JRiver Media Center(媒体管理软件)
android·学习·智能手机·媒体·软件需求
韩凡29 分钟前
HashMap的理解与结构
java·开发语言·哈希算法
会飞的土拨鼠呀41 分钟前
docker部署 outline(栗子云笔记)
笔记·docker·容器
hhzz1 小时前
Spring Boot整合Activiti的项目中实现抄送功能
java·spring boot·后端
初心灬1 小时前
Java 对接coze工作流
java
代衡_Monster1 小时前
通过位运算实现Java逻辑的包含关系
java·java-ee