【java基础】案例代码4

目录

四、集合

(一)Collection

1.Collection集合存储对象并遍历

2.List集合存储学生对象三种遍历方式

3.列表迭代器(ListIterator)

4.ArrayList集合存储学生对象三种遍历方式

5.HashSet集合存储学生对象并遍历

6.自然排序Comparable的使用(TreeSet)

7.比较器排序Comparator的使用(TreeSet)

8.不重复的随机数案例

(二)Map

1.HashMap集合练习之键是String值是Student

2.HashMap集合练习之键是Student值是String

3.集合嵌套之ArrayList嵌套HashMap

4.集合嵌套之ArrayList嵌套HashMap

5.统计字符串中每个字符出现的次数

(三)Collections集合工具类

1.ArrayList集合存储学生并排序


四、集合

set:无序、无索引(只能迭代器或增强for)、不重复 

list:有序、有索引、可重复

map:键不能重复,值可以重复、元素存取无序

(一)Collection

1.Collection集合存储对象并遍历

需求:创建-一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class CollectionDemo {
    public static void main(String[] args) {
        //创建Collection集合对象
        Collection<Student> c = new ArrayList<Student>();

        //创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 = new Student("张曼玉", 35);
        Student s3 = new Student("王祖贤", 33);

        //将学生添加到集合
        c.add(s1);
        c.add(s2);
        c.add(s3);

        //遍历(迭代器)
        Iterator<Student> it = c.iterator();
        while (it.hasNext()) {  //判断
            Student s = it.next();  //获取
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}
public class Student {
    private String name;
    private  int age;

    public Student(){

    }
    public Student(String name, int age){
        this.age = age;
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public int getAge(){
        return age;
    }
    public void setAge(int age){
        this.age = age;
    }
}

2.List集合存储学生对象三种遍历方式

需求:创建-一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

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

public class ListDemo {
    public static void main(String[] args) {
        //创建List集合对象
        List<Student> list = new ArrayList<Student>();

        //创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 = new Student("张曼玉", 35);
        Student s3 = new Student("王祖贤", 33);

        //将学生添加到集合
        list.add(s1);
        list.add(s2);
        list.add(s3);

        //法一:迭代器遍历(集合特有遍历方式)
        Iterator<Student> it = list.iterator();
        while (it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName() + "," + s.getAge());
        }

        System.out.println("--------");

        //法二:for循环遍历(带有索引遍历方式)
        for (int i = 0; i < list.size(); i++) {  //集合长度
            Student s = list.get(i); //带索引的get方法
            System.out.println(s.getName() + "," + s.getAge());
        }

        System.out.println("--------");

        //法三:增强for(最方便的遍历方式)
        for (Student s:list) {  //内部原理是一个iterator迭代器
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}
public class Student {
    private String name;
    private  int age;

    public Student(){

    }
    public Student(String name, int age){
        this.age = age;
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public int getAge(){
        return age;
    }
    public void setAge(int age){
        this.age = age;
    }
}

3.列表迭代器(ListIterator)

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ListIteratorDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();

        list.add("hello");
        list.add("world");
        list.add("java");

        ListIterator<String> lit = list.listIterator();
        while(lit.hasNext()){  //lit.hasPrevious()判断前一个
            String s = lit.next(); //lit.previous()获取前一个
            if(s.equals("world")){
                lit.add("javaee");  //listIterator独有特性,在迭代期间更改
            }
        }

        System.out.println(list);
    }
}

4.ArrayList集合存储学生对象三种遍历方式

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

public class ArrayDemo {
    public static void main(String[] args) {
        //创建List集合对象
        ArrayList<Student> array = new ArrayList<Student>();

        //创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 = new Student("张曼玉", 35);
        Student s3 = new Student("王祖贤", 33);

        //将学生添加到集合
        array.add(s1);
        array.add(s2);
        array.add(s3);

        //法一:迭代器遍历(集合特有遍历方式)
        Iterator<Student> it = array.iterator();
        while (it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName() + "," + s.getAge());
        }

        System.out.println("--------");

        //法二:for循环遍历(带有索引遍历方式)
        for (int i = 0; i < array.size(); i++) {  //集合长度
            Student s = array.get(i); //带索引的get方法
            System.out.println(s.getName() + "," + s.getAge());
        }

        System.out.println("--------");

        //法三:增强for(最方便的遍历方式)
        for (Student s:array) {  //内部原理是一个iterator迭代器
            System.out.println(s.getName() + "," + s.getAge());
        }

        //和list基本完全相同
    }
}
public class Student {
    private String name;
    private  int age;

    public Student(){

    }
    public Student(String name, int age){
        this.age = age;
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public int getAge(){
        return age;
    }
    public void setAge(int age){
        this.age = age;
    }
}

5.HashSet集合存储学生对象并遍历

需求:创建一个存储学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合
要求:学生对象的成员变量值相同,我们就认为是同一个对象
 

import java.util.HashSet;

public class HashSetDemo {
    public static void main(String[] args) {
        //创建HashSet集合对象
        HashSet<Student> hs = new HashSet<>();

        //创建学生对象
        Student s1 = new Student("林青霞",30);
        Student s2 = new Student("张曼玉",35);
        Student s3 = new Student("王祖贤",33);
        Student s4 = new Student("王祖贤",33);

        //把学生添加到集合
        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);

        //遍历集合(增强for)
        for(Student s : hs){
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}
public class Student {
    private String name;
    private  int age;

    public Student(){

    }
    public Student(String name, int age){
        this.age = age;
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public int getAge(){
        return age;
    }

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

    //alt + insert 重写equals和hashCode(用intellij default模板)
    //比较内容时需要重写,不然s3和s4地址不同,算出来结果hash值不一样,元素会重复
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }

6.自然排序Comparable的使用(TreeSet)

需求:存储学生对象并遍历, 创建TreeSet集合使用无参构造方法
要求: 按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
 

public class Student implements Comparable<Student>{
    private String name;
    private int age;

    public Student() {

    }

    public Student(String name, int age) {
        this.age = age;
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    //重写自然排序函数
    @Override
    public int compareTo(Student s) {
        //必须按照排序的主要条件和次要条件来写(年龄、姓名)

        //return 0;  //只输出第一行
        //return 1;  //按照存储顺序正序输出
        //return -1; //按照存储顺序倒序输出
        //int num = s.age - this.age;//按照年龄降序输出
        int num = s.age - this.age;//按照年龄正序输出

        //年龄相同时,按照姓名的字母顺序排序
        int num2 = num == 0 ? this.name.compareTo(s.name) : num;

        return num2;
    }
}
import java.util.TreeSet;

public class ComparableDemo {
    public static void main(String[] args) {
        //创建集合对象
        TreeSet<Student> ts = new TreeSet<Student>();

        //创建集合对象
        Student s1 = new Student("xishi",30);
        Student s2 = new Student("diaochan",35);
        Student s3 = new Student("wangzuxian",33);
        Student s4 = new Student("wangzhaojun", 40);

        Student s5 = new Student("linqingxia",40);

        //把学生添加到集合
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);

        //遍历集合(增强for)
        for(Student s : ts) {
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

7.比较器排序Comparator的使用(TreeSet)

需求:存储学生对象并遍历,创建TreeSet集合使用带参构造方法
要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序

import java.util.Comparator;
import java.util.TreeSet;

public class ComparatorDemo {
    public static void main(String[] args) {
        //创建集合对象 重写compare(T o1,T o2)方法
        TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //this.age - s.age
                //s1,s2
                int num = s1.getAge() - s2.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                return num2;
            }
        });

        //创建集合对象
        Student s1 = new Student("xishi",30);
        Student s2 = new Student("diaochan",35);
        Student s3 = new Student("wangzuxian",33);
        Student s4 = new Student("wangzhaojun", 40);

        Student s5 = new Student("linqingxia",40);
        Student s6 = new Student("linqingxia",40);

        //把学生添加到集合
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);

        //遍历集合(增强for)
        for(Student s : ts) {
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}
public class Student implements Comparable<Student> {
    private String name;
    private int age;

    public Student() {

    }

    public Student(String name, int age) {
        this.age = age;
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    //重写自然排序函数
    @Override
    public int compareTo(Student s) {
        //必须按照排序的主要条件和次要条件来写(年龄、姓名)

        //return 0;  //只输出第一行
        //return 1;  //按照存储顺序正序输出
        //return -1; //按照存储顺序倒序输出
        //int num = s.age - this.age;//按照年龄降序输出
        int num = s.age - this.age;//按照年龄正序输出

        //年龄相同时,按照姓名的字母顺序排序
        int num2 = num == 0 ? this.name.compareTo(s.name) : num;

        return num2;
    }
}

8.不重复的随机数案例

需求:编写一个程序,获取10个1-20之间的随机数,要求随机数不能重复,并在控制台输出

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

public class RandomSet {
    public static void main(String[] args) {
        //随机数:random
        //存储10个:集合
        //不重复:set

        //创建Set集合对象
        Set<Integer> set = new HashSet<Integer>();//不能排序
        //Set<Integer> set = new TreeSet<Integer>();//可以排序
        //没导包可以按alt enter导包

        //创建随机数对象
        Random r = new Random();

        //判断集合长度是不是小于10
        while (set.size() < 10) {
            //产生一个随机数,添加到集合
            int number = r.nextInt(20) + 1;
            set.add(number);
        }

        //遍历结合
        for (Integer i : set) {
            System.out.println(i);
        }
    }
}

(二)Map

1.HashMap集合练习之键是String值是Student

public class Student {
    private String name;
    private int age;

    public Student(){

    }
    public Student(String name, int age){
        this.age = age;
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public int getAge(){
        return age;
    }

    public void setAge(int age){
        this.age = age;
    }
}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapDemo {
    public static void main(String[] args) {
        //创建HashMap集合对象
        HashMap<String, Student> hm = new HashMap<String, Student>();

        //创建学生对象
        Student s1 = new Student("张曼玉", 30);
        Student s2 = new Student("林青霞", 35);
        Student s3 = new Student("王祖贤", 33);

        //把学生添加到集合
        hm.put("it001", s1);
        hm.put("it002", s2);
        hm.put("it003", s3);

        //方式一:键找值
        //用keySet()获取所有键的集合
        Set<String> keySet = hm.keySet();
        //遍历键的集合,获取到每一个键。用增强for实现
        for (String key : keySet) {
            //根据键去找值,用get(Object key)实现
            Student value = hm.get(key);
            System.out.println(key + "," + value.getName() + "," + value.getAge());
        }
        System.out.println("--------");

        //方式二:键值对对象找键和值
        //获取所有键值对集合hm.entrySet(),ctrl alt v
        Set<Map.Entry<String, Student>> entrySet = hm.entrySet();
        //遍历键值对对象的集合,得到每一个键和值
        for (Map.Entry<String, Student> me : entrySet) {
            //根据键值对对象获取键和值
            String key = me.getKey();
            Student value = me.getValue();
            System.out.println(key + "," + value.getName() + "," + value.getAge());
        }
    }
}

2.HashMap集合练习之键是Student值是String

需求:创建一个HashMap集合, 键是学生对象(Student), 值是居住地(String)。存储多个键值对元素,并遍历。
要求保证键的唯一性: 如果学生对象的成员变量值相同,我们就认为是同一个对象

public class Student {
    private String name;
    private int age;

    public Student() {

    }

    public Student(String name, int age) {
        this.age = age;
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}
import java.util.HashMap;
import java.util.Set;

public class HashMapDemo {
    public static void main(String[] args) {
        //创建hashMap集合对象
        HashMap<Student, String> hm = new HashMap<Student, String>();

        //创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 = new Student("张曼玉", 35);
        Student s3 = new Student("王祖贤", 33);

        Student s4 = new Student("王祖贤", 33);

        //把学生添加到集合
        hm.put(s1, "西安");
        hm.put(s2, "武汉");
        hm.put(s3, "郑州");
        hm.put(s4, "北京");//覆盖

        //遍历集合
        Set<Student> keySet = hm.keySet();
        for (Student key : keySet) {
            String value = hm.get(key);
            System.out.println(key.getName() + "," + key.getAge() + "," + value);
        }
    }
}


3.集合嵌套之ArrayList嵌套HashMap

需求:创建一个ArrayList集合, 存储三个元素,每一个元素都是HashMap, 每一个HashMap的键和值都是String, 并遍历

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class ArrayListIncludeHashMap {
    public static void main(String[] args) {
        //创建ArrayList集合
        ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();

        //创建HashMap集合,并添加键值对元素
        HashMap<String, String> hm1 = new HashMap<String, String>();
        hm1.put("孙策", "大乔");
        hm1.put("周瑜", "小乔");
        //把HashMap作为元素添加到Arraylist集合
        array.add(hm1);

        HashMap<String, String> hm2 = new HashMap<String, String>();
        hm2.put("郭靖", "黄蓉");
        hm2.put("杨过", "小龙女");
        //把HashMap作为元素添加到Arraylist集合
        array.add(hm2);

        HashMap<String, String> hm3 = new HashMap<String, String>();
        hm3.put("令狐冲", "任盈盈");
        hm3.put("林平之", "岳灵珊");
        //把HashMap作为元素添加到Arraylist集合
        array.add(hm3);

        //遍历ArrayList集合
        for (HashMap<String, String> hm : array) {
            //遍历HashMap集合
            Set<String> keySet = hm.keySet();
            for (String key : keySet) {
                String value = hm.get(key);
                System.out.println(key + "," + value);
            }
        }
    }
}

4.集合嵌套之ArrayList嵌套HashMap

需求:创建一个HashMap集合, 存储三三个键值对元素,每一个键值对元索的键是String,值是ArrayList,
每一-个ArrayL ist的元素是String,并遍历

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class HashMapIncludeArrayList {
    public static void main(String[] args) {
        //创建HashMap集合
        //键是String,值是ArrayList<String>
        HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();

        //创建ArrayList集合,并添加元素
        ArrayList<String> sgyy = new ArrayList<String>();
        sgyy.add("诸葛亮");
        sgyy.add("赵云");
        //把ArrayList作为元素添加到HashMap集合
        hm.put("三国演义", sgyy);

        ArrayList<String> xyj = new ArrayList<String>();
        xyj.add("唐僧");
        xyj.add("孙悟空");
        //把ArrayList作为元素添加到HashMap集合
        hm.put("西游记", xyj);

        ArrayList<String> shz = new ArrayList<String>();
        shz.add("武松");
        shz.add("鲁智深");
        //把ArrayList作为元素添加到HashMap集合
        hm.put("水浒传", shz);

        //遍历HashMap集合
        Set<String> keySet = hm.keySet();
        for (String key : keySet) {
            System.out.println(key);
            ArrayList<String> value = hm.get(key);
            for (String s : value) {
                System.out.println("\t" + s);
            }
        }
    }
}

5.统计字符串中每个字符出现的次数

需求:键盘录入一个字符串,要求统计字符串中每个字符串出现的次数。
举例:键盘录入"aababcabcdabcde"
在控制台输出: "a(5)b(4)c(3)d(2)e(1)"

import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

public class HashMapDemo {
    public static void main(String[] args) {
        //输入字符串
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String line = sc.nextLine();

        //创建HashMap集合 键Character,值Integer
        //HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
        //TreeMap可以进行排序
        TreeMap<Character, Integer> hm = new TreeMap<Character, Integer>();

        //遍历字符串,得到每一个字符
        for (int i = 0; i < line.length(); i++) {
            char key = line.charAt(i);

            //拿得到的每一个字符作为键到HashMap集合中去找对应的值,看其返回值
            Integer value = hm.get(key);

            if (value == null) {
                //如果返回值是null,说明该字符在HashMap集合中不存在,就把该字符作为键,1作为值存储
                hm.put(key, 1);
            } else {
                //如果返回值不是null,说明该字符在HashMap集合中存在,把该值加一,然后重新存储该字符和对应结果
                value++;
                hm.put(key, value);
            }
        }
        //遍历HashMap集合,得到键和值,按照要求进行拼接
        StringBuilder sb = new StringBuilder();

        Set<Character> keySet = hm.keySet();
        for (Character key : keySet) {
            Integer value = hm.get(key);
            sb.append(key).append("(").append(value).append(")");
        }

        String result = sb.toString();//转换成String

        System.out.println(result);
    }
}

(三)Collections集合工具类

1.ArrayList集合存储学生并排序

需求: ArrayList存储学生对象, 使用Collections对ArrayL ist进行排序
要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
 

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class CollectionsDemo {
    public static void main(String[] args) {
        //创建List集合对象
        ArrayList<Student> array = new ArrayList<Student>();

        //创建学生对象
        Student s1 = new Student("linqingxia", 30);
        Student s2 = new Student("zhangmanyu", 35);
        Student s3 = new Student("wangzuxian", 33);
        Student s4 = new Student("liuyuan", 33);

        //将学生添加到集合
        array.add(s1);
        array.add(s2);
        array.add(s3);
        array.add(s4);

        //使用Collection对ArrayList集合排序
        //sort(list<T>list,Comparator<? super T>c)
        Collections.sort(array, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //按年龄从小到大,相同时按姓名字母顺序
                int num = s1.getAge() - s2.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                return num2;
            }
        });

        //遍历集合
        for (Student s : array) {
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

  • 17
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值