Map集合的常用方法

这篇博客详细介绍了Java集合框架中的HashMap、HashTable和TreeMap。HashMap提供了快速查询,但不是线程安全的;HashTable是线程安全但效率较低;TreeMap基于红黑树,保持元素排序。在多线程环境中,推荐使用CurrentHashMap。此外,还展示了它们在存储和操作上的区别,以及如何在实际场景中选择合适的Map实现。
摘要由CSDN通过智能技术生成

##Map集合

常用方法:

public class Ma {
public void  fa(){

}
public static void main(String[] args){
    Map<String,String> map=new HashMap<String,String>();//添加元素
    map.put("1","2");
    map.put("4","4");
    map.put("7","7");
    extracted(map);
    Set<String> set=map.keySet();
    for(String s:set){
        System.out.print(s+" "+map.get(s));
    }
    System.out.println();
    //获取value的Collection<T>
    Collection<String> a=map.values();
    for(String m:a){
        System.out.print(m);
    }
    System.out.println();
    Set<Entry<String,String>>entrySet=map.entrySet();
    for(Entry<String,String>entry:entrySet){
        System.out.print(entry.getKey()+" "+entry.getValue());
    }
    System.out.println(map.remove("1","2"));
    System.out.println(map);
    System.out.println(map.remove("1"));
    System.out.println(map);
}

private static void extracted(Map<String, String> map) {
    System.out.println(map);
    System.out.print(map.containsKey("1"));//判断集合是否包含指定的键
    System.out.println();
    System.out.print(map.containsValue("2"));//判断集合是否包含指定的值
    System.out.println();
    System.out.println(map.isEmpty());
    System.out.println(map.size());//返回集合中的对的对数
    //KeySet():获取Key的集合Set<T>
}
}

HashMap类的使用

用HashMap类实现控制台输入一句英语,简单统计各个单词出现的次数的功能

public class MapTest {
public static void main(String[] args){
   /* List c=new ArrayList();
    c.add("java");
    c.add("pathon");
    c.add("math");
    c.add("english");
    Iterator iterator=c.iterator();
    while(iterator.hasNext()){
        String str=(String)iterator.next();
        System.out.print(str+" ");
    }*/
    Scanner sc=new Scanner(System.in);
    System.out.println("请输入一句英语,单词间用空格隔开");
    String sentence=sc.nextLine();
    String[] arr=sentence.split("");
    //键代表着单词,值代表着次数
    Map<String,Integer>map=new HashMap<String,Integer>();
    for(int i=0;i<arr.length;i++){
        if(!map.containsKey(arr[i])){
            map.put(arr[i],1);
        }
        else{
            //说明Map中存在该元素
            int num=map.get(arr[i]);
            map.put(arr[i],++num);
        }
    }
    System.out.println("统计单词出现的个数,结果如下");
    Set<String>set=map.keySet();
    Iterator<String>iterator1=set.iterator();
    while(iterator1.hasNext()){
        String key=(String)iterator1.next();
        Integer value=map.get(key);
        System.out.println(key+"出现的次数为"+value);
    }
}
}

TreeMap类的使用

用TreeMap类实现向数字图书馆添加书籍的功能

package com;

import java.util.TreeMap;
import java.util.Comparator;
public class TreeMapTest {
public static void main(String[] args) {
    TreeMap<String, Book> map = new TreeMap<String, Book>(new MyComparator());
    map.put("B45678",new Book("B45678","钢铁是怎样炼成的","尼古拉",56));
    map.put("B678",new Book("B678","世界是平的","弗里德曼",56));
    map.put("D89",new Book("D89","java编程思想","kobe",56));
    map.put("A15678",new Book("A15678","高等数学","joms",56));
    System.out.println(map);
}
}
class Book{

String bookno;
String bookName;
String author;
int price;
public String getBookno(){
    return bookno;
}
public String getBookName(){
    return bookName;
}
public void setBookName(String bookName){
    this.bookName=bookName;
}
public String getAuthor(){
    return author;
}
public void setAuthor(String author){
    this.author=author;
}
public int getPrice(){
    return price;
}
public void setPrice(int price){
    this.price=price;
}
@Override
public String toString(){

    return "Book[bookno="+bookno+",bookName="+bookName+",author="+author+",price="+price+"]";
}
public Book(String bookno,String bookName,String author,int price){
    super();
    this.bookno=bookno;
    this.bookName=bookName;
    this.author=author;
    this.price=price;
}
}
class MyComparator implements Comparator<String>{
@Override
public int compare(String o1,String o2){
    if(o1.length()==o2.length()){
        return o1.compareTo(o2);
    }
    return o1.length()-o2.length();
}
}

##HashMap类和HashTable类对比

1、继承的父类不同,HashMap继承的是AbstractMap类,而HashTable继承的是Dictionary类。

2、初始容量和扩容增量不同,HashMap初始容量为16个字节,扩容增量为原来的两倍,而HashTable初始容量为11个字节,扩容增量为原来的2倍+1。

3、HashMap允许存在null值,HashTable不允许存在null值。

4、HashMap为线程不安全的,且不同步,在多线程并发过程可能会产生死锁问题,需要自己动手处理,而HashTable是线程安全的,在每个方法中都加了synchronized同步锁,就相当于是加了同步锁的HashMap。

5、迭代器相同,两者都使用了Iterator。

6、添加键/值对时的哈希码取值算法不同,HashMap添加元素时使用的是自定义哈希算法,而HashTable没用自定义哈希算法,直接采用的是键的hashCode()方法。

注意:HashMap比HashTable效率高,当需要多线程操作时可以使用CurrentHashMap。CurrentHashMap是线程安全的,而且效率要高于HashTable,因为CurrentHashMap采用了分段锁,并不对整段数据进行锁定。

##HashMap类和TreeMap类对比

1、HashMap通过hashCode()方法对其内容进行快速查询,而TreeMap是基于红黑树的一种访问的Map,所有的元素都保持着某种固定的顺序。如果你需要得到一个有序的结果就应该使用TreeMap(HashMap中元素排列顺序是不固定的)。

2、两者的存取的时间复杂度都是o(log(n))。

3、两者都是非线程安全的。

4、HashMap适用于在Map中插入、删除和定位元素,TreeMap适用于按自然
顺序或自定义顺序遍历键。/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值