JAVA入门————Map AND 嵌套 AND 工具类

Map接口

  • 概念:存储键值映射关系的数据 一个键对应一个值 是一个接口
  • 一个映射不能包含重复的键
  • Map接口下的三个实现类 HashMap , LinkedHashMap TreeMap
  • 键相同 值覆盖:第一次储存一个键值对时,返回true 第二次储存同一对键值对时 返回false

HashMap——无序

  • HashMap键的数据结构是哈希表
  • 线程不安全 允许null值和null键
  • Map——双列集合 Set List —— 单列集合
  • HashSet用HashMap存储
eg:	HashMap<String, String> map = new HashMap<>();
        map.put("1","物联网工程");
        map.put("2","软件工程");
        map.put("3","计算机科学与技术");
        System.out.println(map);————输出有序
eg:	HashMap<Integer, Student1> hashmap = new HashMap<>();
        hashmap.put(1, new Student1("余小晚", 25));
        hashmap.put(2,new Student1("肖正国",30));
        hashmap.put(3,new Student1("周海潮",32));
        hashmap.put(4,new Student1("张离",28));
        hashmap.put(2,new Student1("陈山",30));
        System.out.println(hashmap);
        输出:{1=Student1{name='余小晚', age=25}, 2=Student1{name='陈山', age=30}, 3=Student1{name='周海潮', age=32}, 4=Student1{name='张离', age=28}}————重写了toString()
......
@Override
    public String toString() {
        return "Student1{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student1 student1 = (Student1) o;
        return age == student1.age &&
                Objects.equals(name, student1.name);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name, age);————利用哈希算法排除相同的数据
    }
V.put (K key, V value)——存储键值对
V.remove(K key)——移除键值对
V.isEmpty()——判断集合是否为空
V.size()———获取集合的长度
V.containsKey(K key)——判断集合是否包含此键
V.containsValue(V value)——判断集合是否包含此值
V.clear()——清空集合
V.keySet()———获取所有键的集合
V.values()——获取所有值的集合
eg:	HashMap<Integer, String> hashmap = new HashMap<>();
        hashmap.put(1,"余小晚");
        hashmap.put(2,"肖正国");
        hashmap.put(3,"周海潮");
        hashmap.put(4,"张离");
        hashmap.put(5,"陈山");
        String value = hashmap.remove(3);
        System.out.println(value);————输出此键对应的值
        boolean b = hashmap.isEmpty();
        int size = hashmap.size();
        boolean b1 = hashmap.containsKey(2);
        boolean b2 = hashmap.containsValue("陈山");
        hashmap.clear();
        System.out.println(hashmap);——————输出:{}
         Set<Integer> keys = hashmap.keySet();
        Collection<String> values = hashmap.values();
  • 遍历集合
 eg:	 方法一:根据键找值
 		HashMap<String,String> hm = new HashMap<>();
        hm.put("江夏","林星然");
        hm.put("肖正国","余小晚");
        hm.put("陈山","张离");
        hm.put("周海潮","孤独");
        Set<String> keys = hm.keySet();——————取出所有的键放进一个集合
        for (String k : keys) {
            System.out.println(k+"==="+hm.get(k));
        }
接口 Map.Entry<K, V>
V.entrySet()———取出键值对为一个集合
K.getKey ()——返回与此项对应的键
K.getValue ()——返回与此项对应的值
eg:	方法二:取出键值对 在找到对应的键与值
		Set<Map.Entry<String, String>> entries = hm.entrySet();————取出所有的键值对放进一个集合
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"==="+value);
        }

自定义类遍历集合

eg:	HashMap<Integer,Student1> hm = new HashMap<>();
        hm.put(2,new Student1("小任",20));
        hm.put(3,new Student1("小董",21));
        hm.put(4,new Student1("小高",20));
        hm.put(1,new Student1("小沈",19));
        hm.put(5,new Student1("小崔",20));
        ——————遍历1  键找值
        Set<Integer> key = hm.keySet();
        for (Integer keyset : key) {
            System.out.println(keyset+"==="+hm.get(keyset));
        }
        System.out.println("=======================");
        ————————遍历2  取出键值对
        Set<Map.Entry<Integer, Student1>> 键值对 = hm.entrySet();
        for (Map.Entry<Integer, Student1> entry : 键值对) {
            System.out.println(entry.getKey()+"======"+entry.getValue());
        }

LinkedHashSet——有序

  • 概念:键唯一且有序 键的数据结构是哈希表和链表 哈希表——唯一 链表——有序
  • 遍历集合 forEach( )
eg:	LinkedHashMap<Integer,String> hashmap = new LinkedHashMap<>();
        hashmap.put(1,"余小晚");
        hashmap.put(2,"肖正国");
        hashmap.put(3,"周海潮");
        hashmap.put(4,"张离");
        hashmap.put(5,"陈山");
        hashmap.forEach(new BiConsumer<Integer, String>() {
            @Override
            public void accept(Integer key, String value) {
                System.out.println(key+"==="+value);
            }
        });

TreeMap——按key排序

  • 是红黑二叉树算法的实现——根据键的自然顺序排序

遍历集合方法一:自然排序
自定义类中需要实现Comparable<>接口 重写 public int compareTo(Object o)方法

eg:	public static void main(String[] args) {
        TreeMap<Integer,Student2> tm = new TreeMap<>();
        tm.put(1,new Student2("余小晚", 25));
        tm.put(2,new Student2("肖正国",30));
        tm.put(3,new Student2("周海潮",32));
        tm.put(4,new Student2("张离",28));
        tm.put(5,new Student2("陈山",30));
        tm.forEach(new BiConsumer<Integer, Student2>() {
            @Override
            public void accept(Integer integer, Student2 student2) {
                System.out.println(student2.getName()+"==="+student2.getAge());
            }
        });

遍历集合方法二 :比较器排序

import TreeSet.Student1;
import java.util.Comparator;
import java.util.TreeMap;
import java.util.function.BiConsumer;
public class demo2 {
    public static void main(String[] args) {
        TreeMap<Student1,Integer> tm = new TreeMap<>(new Comparator<Student1>() {
            @Override
            public int compare(Student1 s1, Student1 s2) {
                int num=s1.getName().length()-s2.getName().length();
                int num2=num==0?s1.getName().compareTo(s2.getName()):num;
                int num3=num2==0?s1.getAge()-s2.getAge():num2;
                return num3;
            }
        });
        tm.put(new Student1("余小晚",25),1);
        tm.put(new Student1("肖正国",30),2);
        tm.put(new Student1("周海潮",32),3);
        tm.put(new Student1("张离",28),4);
        tm.put(new Student1("陈山",30),5);
        tm.forEach(new BiConsumer<Student1, Integer>() {
            @Override
            public void accept(Student1 student1, Integer integer) {
                System.out.println(integer+student1.getName()+":"+student1.getAge());
            }
        });
    }
}

需求:统计字符串中每个字符出现的次数 结果输出:a(6) s(3) d(4) f(1)

import java.util.HashMap;
import java.util.Scanner;
import java.util.function.BiConsumer;
public class test2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一段字符串:");
        String s = sc.nextLine();
        HashMap<Character, Integer> hm = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {  //  aasdfg
            char c = s.charAt(i);   // ch = a  ch = a
            if(!hm.containsKey(c)){
                hm.put(c,1);    // put(a,1)
            }else{
                Integer num = hm.get(c);  //根据键找值  // num = 1
                num++;    // num = 2
                hm.put(c,num);   // put(a,2)
            }
        }
        //遍历集合
        hm.forEach(new BiConsumer<Character, Integer>() {
            @Override
            public void accept(Character character, Integer integer) {
                System.out.print(character+"("+integer+")"+" ");
            }
        });
    }
}

取出大集合中的小集合

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;

public class test3 {
    public static void main(String[] args) {
        HashMap<String,Integer> hm = new HashMap<>();
        hm.put("张三",20);
        hm.put("李四",21);
        HashMap<String, Integer> hm2 = new HashMap<>();
        hm2.put("王五",22);
        hm2.put("赵六",23);
        HashMap<String,HashMap<String,Integer>> hashMap = new HashMap<>();
        hashMap.put("基础班",hm);
        hashMap.put("就业班",hm2);

        ——————方法一:取出键值对
        Set<Map.Entry<String, HashMap<String,Integer>>> entries = hashMap.entrySet();//取出hashMap里的键值对
        for (Map.Entry<String, HashMap<String, Integer>> entry : entries) {
            System.out.println(entry.getKey());   //  输出:hashMap里的key
            HashMap<String, Integer> value = entry.getValue(); //获取hashMap里的value 小集合
            Set<Map.Entry<String, Integer>> entries1 = value.entrySet(); // 取出小集合里的键值对
            for (Map.Entry<String, Integer> stringIntegerEntry : entries1) {
                System.out.println("      "+stringIntegerEntry.getKey()+"   "+stringIntegerEntry.getValue());
            }   //获取小集合中的键与值
            System.out.println();
        }
        System.out.println("--------------------------------");

        ——————方法二:forEach遍历
        hashMap.forEach(new BiConsumer<String, HashMap<String, Integer>>() { // forEach遍历
            @Override
            public void accept(String s, HashMap<String, Integer> stringIntegerHashMap) {
                System.out.println(s);
                stringIntegerHashMap.forEach(new BiConsumer<String, Integer>() {
                    @Override
                    public void accept(String s, Integer integer) {
                        System.out.println("      "+s+"   "+integer);
                    }
                });
            }
        });
        System.out.println("--------------------------------");
        ——————方法三:根据键找值
        Set<String> strings = hashMap.keySet();//取出hashMap中所有的键
        for (String string : strings) {
            System.out.println(string);
            HashMap<String, Integer> stringIntegerHashMap = hashMap.get(string); //根据hashMap中的键找小集合
            Set<String> strings1 = stringIntegerHashMap.keySet();//取出小集合中所有的键
            for (String s : strings1) {
                System.out.println("      "+s+"   "+stringIntegerHashMap.get(s));
            }
        }
        ——————输出:就业班
     						 王五   22
     						 赵六   23

					基础班
     						 李四   21
     						 张三   20
    }
}

例题

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class test5 {
    public static void main(String[] args) {
        HashMap<String, String> sgmap = new HashMap<>();
        sgmap.put("周瑜", "小乔");
        sgmap.put("吕布", "貂蝉");
        HashMap<String, String> sdmap = new HashMap<>();
        sdmap.put("郭靖", "黄蓉");
        sdmap.put("杨过", "小龙女");
        sdmap.put("杨过", "郭襄");
        HashMap<String, String> xamap = new HashMap<>();
        xamap.put("令狐冲", " 任盈盈");
        xamap.put("林平之", "岳灵珊");
        ArrayList<HashMap<String,String>> list = new ArrayList<>();
        list.add(sgmap);
        list.add(sdmap);
        list.add(xamap);

        for (HashMap<String, String> stringStringHashMap : list) {
            Set<Map.Entry<String, String>> entries = stringStringHashMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                System.out.println(entry.getKey()+"——"+entry.getValue());
            }
            System.out.println();
        }
    }
}

工具类

  • 针对collection集合提供的工具类
Collections.binarySearch( (List list, T key)——二分查找
 eg;	ArrayList<Integer> integers = new ArrayList<>();
        integers.add(123);
        integers.add(456);
        integers.add(555);
        integers.add(0);
        integers.add(333);
        int i = Collections.binarySearch(integers, 555);
        System.out.println(i);————输出:2
sort(List list)————自然排序
 eg:	Collections.sort(integers);
        System.out.println(integers);————输出:[0, 123, 333, 456, 555]
sort(List list, Comparator<? super T> c) ——————比较器排序
eg:	Collections.sort(integers, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });
        System.out.println(integers);————输出:[0, 123, 333, 456, 555]
获取最值
eg:	Integer max = Collections.max(integers);
        System.out.println(max);————输出:555
        Integer min = Collections.min(integers);
        System.out.println(min);————输出:0
shuffle(List<?> list)————根据默认顺序打乱集合
eg:	Collections.shuffle(integers);
        System.out.println(integers);
shuffle(List<?> list, Random rnd) ————根据随机顺序打乱集合
eg:	Random random = new Random();
        Collections.shuffle(integers,random);
        System.out.println(integers);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值