Set、Map集合案例代码实现-Java基础学习总结

7月17,18日学习内容运用

Set集合常用方法介绍

add(E e):相集合中增加元素

ArrayList<Object> objects = new ArrayList<>();
        boolean b = objects.add(12);//向集合中增加元素,增加成功返回true,否则返回false;
        System.out.println(b);
运行结果:true

addAll(Collection c):两个集合取并级

ArrayList<Object> objects = new ArrayList<>();
        objects.add(12);//向集合中增加元素,增加成功返回true,否则返回false;
        objects.add(14);
        ArrayList<Object> objects1 = new ArrayList<>();
        objects.add(121);
        boolean b = objects.addAll(objects1);//两个集合取并集,并存储在objects集合中,成功返回true
        System.out.println(objects);
        System.out.println(b);

clear():移除集合中所有元素

        ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add(121);
        objects1.add(134);
        objects1.clear();
        System.out.println(objects1);

contains(Object o):判断是否包含指定元素

 ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add(121);
        boolean b1 = objects1.contains(5);//判断集合中是否有指定元素,有则返回true,无false
        System.out.println(b1);

isEmpty():判断集合是否为空

ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add(121);
        boolean b1 = objects1.isEmpty();//判断集合中是否为空,空返回true,否则返回false
        System.out.println(b1);

remove(Object o):移除指定元素

ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add(121);
        boolean b1 = objects1.remove(12);//判断集合中是否为空,空返回true,否则返回false
        System.out.println(b1);

removeAll(Collection c):移除于c集合相同元素

 ArrayList<Object> objects = new ArrayList<>();
        objects.add(124);
        objects.add(15);
        ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add(124);
        objects1.add(155);
        boolean b = objects.removeAll(objects1);//移除objects中,与objects1相同的元素
        System.out.println(b);
        System.out.println(objects);

size():获取集合长度

ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add(121);
        objects1.size();//判断集合中是否为空,空返回true,否则返回false
        System.out.println(b1);

clone():元素克隆

 ArrayList<Object> objects = new ArrayList<>();;
        objects.add(124);
        objects.add(15);
        ArrayList<Object> objects1 = new ArrayList<>();
        Object o = objects.clone();
        System.out.println(o);

retainAll():两个集合取交集;

ArrayList<Object> objects = new ArrayList<>();;
        objects.add(124);
        objects.add(15);
        ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add(124);
        objects1.add(134);
        objects1.add(145);
        boolean b1 = objects.retainAll(objects1);//获取两个集合的交集
        System.out.println(b1);
        System.out.println(objects);

Set集合相关案例

1.分包编写登录注册案例

实现接口类功能
public class dLImpl implements dL {
ArrayList dengLus;
String s=null,s1=null;
@Override
public void zhuce() {
dengLus = new ArrayList<>();
// dengLu dengLu = new dengLu();
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println(“请输入用户名:”);
s = scanner.nextLine();
String regx="[A-Z]{6,16}";
boolean b = s.matches(regx);
if(b){
break;
}else{
System.out.println(“用户名格式不对,请重新输入”);
}
}
while (true){
String regx="[0-9]{6,16}";
System.out.println(“请输入密码:”);
s1 = scanner.nextLine();
boolean b = s1.matches(regx);
if(b){
break;
}else{
System.out.println(“用户名格式不对,请重新输入”);}}
dengLu dengLu = new dengLu(s,s1);
dengLus.add(dengLu); }

@Override
public void denglu() {
Scanner scanner = new Scanner(System.in);
System.out.println(“请输入用户名:”);
String s = scanner.nextLine();
System.out.println(“请输入密码:”);
String s1 = scanner.nextLine();
for (dengLu lus : dengLus) {
if (lus.getName().equals(s)&&lus.getPassword().equals(s1)){
System.out.println(“登陆成功”);
}else{
System.out.println(“用户未注册”);
}}}}


main函数实现
public static void main(String[] args) {
System.out.println(“欢迎使用本系统”);
System.out.println(“菜单选项:1.注册 2.登陆 3.退出”);
dLImpl dL = new dLImpl();
while (true){
System.out.println(“请选择:”);
Scanner scanner = new Scanner(System.in);
int i =0;
while (true){
if(scanner.hasNextInt()){
i=scanner.nextInt();
break;
}else{
System.out.println(“格式错误,请重新输入”);
scanner = new Scanner(System.in); } }
switch(i){
case 1:
dL.zhuce();
break;
case 2:
dL.denglu();
break;
case 3:
default:
System.exit(0);
break;}}}

2.存储自定义对象到HashSet集合中,并遍历


HashSet录入,遍历实现
HashSet<Student> ts = new HashSet<>();
ts.add(new Student("zhangsan", 19));
ts.add(new Student("zhangsan", 19));
ts.add(new Student("lisi", 20));
ts.add(new Student("wangwu", 22));
for (Student s : ts) {
    System.out.println(s.getName()+":"+s.getAge());
}
<--------------------------------------------------->
student类实现
class Student {
private String name;
private int age;
public Student(){}

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
       if (o == null || getClass() != o.getClass()) return false;//如若不进行equals方法重写,在存储学生对象时,会出现重复对象
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

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

    public Student(String name, int age){
this.name = name;
this.age = age;
}
public void show () {
System.out.println(name +"..."+age);
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}

3、存储自定义对象到TreeSet集合中,并遍历

a)采用自然排序方式(即采用无参构造)
class Student implements Comparable<Student>{
private String name;
private int age;
public Student(){}
public Student(String name, int age){
this.name = name;
this.age = age;
}
    @Override
    public String toString() {
        return "Student{" +
               "name='" + name + '\'' + ", age=" + age +'}';    }
    public void show () {System.out.println(name +"..."+age);
}
public String getName(){
return name;}
public int getAge(){return age;
}
  @Override    
  public int compareTo(Student o) {
       int num = this.name.compareTo(o.name);
        int num1=num==0?this.age-o.age:num ;
        return num1;    }}
TreeSet<Student> ts = new TreeSet<Student>();
ts.add(new Student("zhangsan", 19));
ts.add(new Student("zhangsan", 19));
ts.add(new Student("lisi", 20));
ts.add(new Student("wangwu", 22));
for (Student s : ts) {
   s.show();}
b)采用比较器排序方式
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
   @Override
   public int compare(Student s1, Student s2) {
           int num1 =s1.getName().compareTo(s2.getName());        int num2 = (num1 == 0) ? (s1.getAge() - s2.getAge()) : num1;
       return num2;   }});
ts.add(new Student("zhangsan", 19));
ts.add(new Student("zhangsan", 19));
ts.add(new Student("lisi", 20));
ts.add(new Student("wangwu", 22));
for (Student s : ts) 
    s.show();
}

4、完成键盘录入学生信息按照总分排序后输出在控制台,并测试

需求:键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩)
  按照总分从高到低输出到控制台
public static void main(String[] args) {
    TreeSet<Student> students = new TreeSet<>(new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            int i = o1.toal() - o2.toal();
            int i1=i==0?o1.getName().compareTo(o2.getName()):i;
            return -i1;
        }
    });
    Scanner scanner;
    for (int i = 0; i < 5; i++) {
        scanner = new Scanner(System.in);
        System.out.println("请输入第"+(i+1)+"位学生名字:");
        String s = scanner.nextLine().trim();
        System.out.println("请输入第"+(i+1)+"位学生数学成绩:");
        int i1 = scanner.nextInt();
        System.out.println("请输入第"+(i+1)+"位学生语文成绩:");
        int i2 = scanner.nextInt();
        System.out.println("请输入第"+(i+1)+"位学生英语成绩:");
        int i3 = scanner.nextInt();
        Student student = new Student(s, i1, i2, i3);
        students.add(student);
    }
    System.out.println(students);
    System.out.println("--------------------------------");
    System.out.println("姓名"+"\t"+"数学成绩"+"\t"+"语文成绩"+"\t"+"英语成绩");
    for (Student student : students) {    System.out.println(student.getName()+"\t"+student.getMathScore()+"\t"+student.getChinScore()+"\t"+student.getEngScore());
    }
}

5.产生10个1-100之间的随机数要求随机数不能重复,并测试

需求:编写一个程序,获取101100的随机数
              要求随机数不能重复,并把最终的随机数输出到控制台。
HashSet<Integer> integers = new HashSet<Integer>();
Random random = new Random();
while(integers.size()<10){
    int i = random.nextInt(100) + 1;
    integers.add(i);
}
System.out.println(integers);

Map集合常用方法介绍

public V put(K key, V value):存取键,以及对应的值
public void clear(): 清除所有元素
public V remove(Object key): 移除指定值
public boolean containsKey(Object key): 是否包含指定键
public boolean containsValue(Object value): 是否包含指定值
public boolean isEmpty(): 是否为空
public Set> entrySet():获取所有键值对
public V get(Object key): 获取指定键的值
public Set keySet() : 获取所有键
public Collection values(): 或取所有值
public int size():获取长度

Collections集合常用方法介绍

public static void sort(List list) : 快速排序
public static int binarySearch(List list,T key):使用二分搜索法搜索指定列表,以获得指定对象
public static T max(Collection coll) 根据元素的自然顺序,返回给定 collection 的最大元素
public static void reverse(List list) 反转指定列表中元素的顺序。
public static void shuffle(List list) 打乱集合
public static void sort(List list, Comparator c) 根据指定比较器产生的顺序对指定列表进行排序。

Map集合的遍历方式

1.使用keyset()方法,获取所有键,此时返回set集合,遍历集合,使用get(key)方法,获取对应的值
2.使用entryset()方法,获取所有键,此时返回set集合,遍历集合,使用getkey(),getvalue()方法,获取对应的值

Collection与Collections的区别

Collections此类完全由在 collection 上进行操作或返回 collection 的静态方法组成。它包含在 collection 上操作的多态算法,即“包装器”,包装器返回由指定 collection 支持的新 collection,以及少数其他内容。

Map集合相关案例

1.编写程序,统计一个字符串中每个字符出现的次数

HashMap<Character, Integer> map = new HashMap<>();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一窜字符");
String s = scanner.nextLine();
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if(!map.containsKey(c)){
        map.put(c,1);
    }else{
        Integer integer = map.get(c);
        integer++;
        map.put(c,integer);
    }
}

2、请编写程序,存储自定义对象到HashMap集合中,并采用两种方式遍历

1.keyset()方法
HashMap<Car, String> tm = new HashMap<Car, String>();
tm.put(new Car("宝马X5", 2014), "Tom");
tm.put(new Car("宝马X5", 2014), "David");
tm.put(new Car("奥迪Q7", 2014), "Jim");
tm.put(new Car("奥迪A4L", 2014), "Kevin");
Set<Car> cars = tm.keySet();
for (Car car : cars) {
    String value = tm.get(car);
    System.out.println(car.getBrand() + "--" + car.getYear() + "--"
            + value);
}
 2.entrySet()方法
HashMap<Car, String> tm = new HashMap<Car, String>();
tm.put(new Car("宝马X5", 2014), "Tom");
tm.put(new Car("宝马X5", 2014), "David");
tm.put(new Car("奥迪Q7", 2014), "Jim");
tm.put(new Car("奥迪A4L", 2014), "Kevin");
Set<Map.Entry<Car, String>> entries1 = tm.entrySet();
for (Map.Entry<Car, String> entry : entries1) {
    Car  key = entry.getKey();
    String value = entry.getValue();
    System.out.println( key.getBrand() + "--" + key.getYear() + "--"
            + value);
}

3、请编写程序,存储自定义对象到TreeMap集合中,并采用两种方式遍历

采用有参构造,重写Comparator中的Compare方法
1. TreeMap<Car, String> tm = new TreeMap<Car, String>(
        new Comparator<Car>() {
            @Override
            public int compare(Car c1, Car c2) {
                int num1 = c1.getYear() - c2.getYear();
                int num2 = (num1 == 0) ? (c1.getBrand().compareTo(c2
                        .getBrand())) : num1;
                return num2;
            }
        });
tm.put(new Car("宝马X5", 2014), "Tom");
tm.put(new Car("宝马X5", 2014), "David");
tm.put(new Car("奥迪Q7", 2014), "Jim");
tm.put(new Car("奥迪A4L", 2014), "Kevin");
Set<Car> cars = tm.keySet();
for (Car car : cars) {
    String value = tm.get(car);
    System.out.println(car.getBrand() + "--" + car.getYear() + "--"
            + value);
}
2. TreeMap<Car, String> tm = new TreeMap<Car, String>(
        new Comparator<Car>() {
            @Override
            public int compare(Car c1, Car c2) {
                int num1 = c1.getYear() - c2.getYear();
                int num2 = (num1 == 0) ? (c1.getBrand().compareTo(c2
                        .getBrand())) : num1;
                return num2;
            }
        });
tm.put(new Car("宝马X5", 2014), "Tom");
tm.put(new Car("宝马X5", 2014), "David");
tm.put(new Car("奥迪Q7", 2014), "Jim");
tm.put(new Car("奥迪A4L", 2014), "Kevin");
Set<Map.Entry<Car, String>> entries1 = tm.entrySet();
for (Map.Entry<Car, String> entry : entries1) {
    Car  key = entry.getKey();
    String value = entry.getValue();
    System.out.println( key.getBrand() + "--" + key.getYear() + "--"
            + value);
}

4、请编写程序,完成集合嵌套,并遍历
形式如下:

		 jc	基础班
				张三		20
				李四		22
		jy	就业班
				王五		21
				赵六		23

HashMap嵌套HashMap
HashMap嵌套ArrayList

public static void main(String[] args) {
    HashMap<String, Integer> jcdmap = new HashMap<>();
    jcdmap.put("张三", 20);
    jcdmap.put("李四",22);
    HashMap<String, Integer> jedmap2 = new HashMap<>();
    jedmap2.put("王五",21);
    jedmap2.put("赵六",23);
    HashMap<String, HashMap<String, Integer>> map1 = new HashMap<>();
    map1.put("基础班",jcdmap);
    HashMap<String, HashMap<String, Integer>> map2 = new HashMap<>();
    map2.put("就业班",jedmap2);
    HashMap<String, HashMap<String, HashMap<String, Integer>>> jcmap = new HashMap<>();
    jcmap.put("jc",map1);
    HashMap<String, HashMap<String, HashMap<String, Integer>>> jemap = new HashMap<>();
    jemap.put("jy",map2);
    ArrayList< HashMap<String, HashMap<String, HashMap<String, Integer>>>> list = new ArrayList<>();
    list.add(jcmap);
    list.add(jemap);
    for (HashMap<String, HashMap<String, HashMap<String, Integer>>> map : list) {
        Set<String> set = map.keySet();
        for (String s : set) {
            //System.out.println(s+"\n");//打印 jc,jy
            HashMap<String, HashMap<String, Integer>> hashMap = map.get(s);
            Set<String> strings = hashMap.keySet();//基础班,就业班
            for (String string : strings) {
                System.out.println(s+"   "+string);//打印 jc,jy
                HashMap<String, Integer> hashMap1 = hashMap.get(string);
                Set<String> set1 = hashMap1.keySet();
                for (String s1 : set1) {
                    Integer integer = hashMap1.get(s1);
                    System.out.println("     "+s1+"   "+integer);
                }
            }
        }
    }
}

你可能感兴趣的:(Set、Map集合案例代码实现-Java基础学习总结)