黑马程序员——JAVA集合
来源:互联网 发布:沉迷网络的哲学文章 编辑:程序博客网 时间:2024/05/17 07:17
----<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! ------
Map、HashMap、TreeMap
Map:一次添加一对元素,Collection一次添加一个元素。
Map也称为双列集合,Collection集合称为单列集合。
其实Map集合中存储的就是键值对。
map集合中必须保证键的唯一性。
Map也称为双列集合,Collection集合称为单列集合。
其实Map集合中存储的就是键值对。
map集合中必须保证键的唯一性。
常用方法:
1、添加
value put(key,value):返回前一个和key关联的值,如果没有返回null。
2、删除
void clear():清空map集合。
value remove(Object key):根据指定的key删除这个键值对。
3、判断
boolean containsKey(key);
boolean containsValue(value);
boolean isEmpty();
4、获取
value get(key):通过键获取值,如果没有该键返回null。
当然可以通过返回null,来判断是否包含指定键。
int size():获取键值对个数。
1、添加
value put(key,value):返回前一个和key关联的值,如果没有返回null。
2、删除
void clear():清空map集合。
value remove(Object key):根据指定的key删除这个键值对。
3、判断
boolean containsKey(key);
boolean containsValue(value);
boolean isEmpty();
4、获取
value get(key):通过键获取值,如果没有该键返回null。
当然可以通过返回null,来判断是否包含指定键。
int size():获取键值对个数。
示例1:
- import java.util.HashMap;
- import java.util.Map;
- public class MapDemo{
- public static void main(String[] args){
- Map<Integer,String> map = new HashMap<Integer,String>();
- method(map);
- }
- public static void method(Map<Integer,String> map){ //学号和姓名
- //添加元素
- System. out.println(map.put(8,"旺财" ));
- System. out.println(map.put(8,"小强" ));
- System. out.println(map);
- map.put(2, "张三");
- map.put(7, "赵六");
- System. out.println(map);
- //删除
- System. out.println("remove:" + map.remove(2));
- //判断
- System. out.println("containsKey:" + map.containsKey(7));
- //获取
- System. out.println("get:" + map.get(7));
- }
- }
运行结果:
获取Map集合元素并打印方式一:
示例2:
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- public class MapDemo{
- public static void main(String[] args){
- Map<Integer,String> map = new HashMap<Integer,String>();
- method(map);
- }
- public static void method(Map<Integer,String> map){
- map.put(8, "王五");
- map.put(2, "赵六");
- map.put(7, "小强");
- map.put(6, "旺财");
- //取出map中的所有元素。
- //原理,通过keySet方法获取map中所有的键所在的set集合,在通过set的迭代器获取到每一个键。
- //再对每一个键通过map集合的get方法获取其对应的值即可。
- Set<Integer> keySet = map.keySet();
- Iterator<Integer> it = keySet.iterator();
- while(it.hasNext()){
- Integer key = it.next();
- String value = map.get(key);
- System.out.println(key + ":" + value);
- }
- }
- }
获取Map集合元素并打印方式二:
示例3:
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- public class MapDemo{
- public static void main(String[] args){
- Map<Integer,String> map = new HashMap<Integer,String>();
- method(map);
- }
- public static void method(Map<Integer,String> map){
- map.put(8, "王五");
- map.put(2, "赵六");
- map.put(7, "小强");
- map.put(6, "旺财");
- /*
- 通过Map转成Set就可以迭代。
- 找到了另一个方法,entrySet。
- 该方法将键和值的映射关系作为对象存储到了Set集合中,而这个映射关系的类型就是Map.Entry类型
- */
- Set<Map.Entry<Integer,String>> entrySet = map.entrySet();
- Iterator<Map.Entry<Integer,String>> it = entrySet.iterator();
- while(it.hasNext()){
- Map.Entry<Integer,String> me = it.next();
- Integer key = me.getKey();
- String value = me.getValue();
- System. out.println(key + ":" + value);
- }
- }
- }
获取Map集合元素并打印方式三:
示例4:
- import java.util.Collection;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- public class MapDemo{
- public static void main(String[] args){
- Map<Integer,String> map = new HashMap<Integer,String>();
- method(map);
- }
- public static void method(Map<Integer,String> map){
- map.put(8, "王五");
- map.put(2, "赵六");
- map.put(7, "小强");
- map.put(6, "旺财");
- Collection<String> values = map.values();
- Iterator<String> it = values.iterator();
- while(it.hasNext()){
- System. out.println(it.next());
- }
- }
- }
Map常用的子类:
|--Hashtable:内部结构是哈希表,是同步的。不允许null作为键,null作为值。
|--Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。
|--HashMap:内部结构式哈希表,不是同步的。允许null作为键,null作为值。
|--TreeMap:内部结构式二叉树,不是同步的。可以对Map集合中的键进行排序。
|--Hashtable:内部结构是哈希表,是同步的。不允许null作为键,null作为值。
|--Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。
|--HashMap:内部结构式哈希表,不是同步的。允许null作为键,null作为值。
|--TreeMap:内部结构式二叉树,不是同步的。可以对Map集合中的键进行排序。
hashSet实现Set接口,由哈希表(实际上是一个HashMap实例)支持。
示例5:
- import java.util.HashMap;
- import java.util.Iterator;
- class Student {
- private String name;
- private int age;
- public Student(){
- }
- public Student(String name,int age){
- this.name = name;
- this.age = age;
- }
- public void setName(String name){
- this.name = name;
- }
- public String getName(){
- return this .name;
- }
- public void setAge(int age){
- this.age = age;
- }
- public int getAge(){
- return this .age;
- }
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + age;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- return result;
- }
- public boolean equals(Object obj) {
- if (this == obj)
- return true ;
- if (obj == null)
- return false ;
- if (getClass() != obj.getClass())
- return false ;
- Student other = (Student) obj;
- if (age != other.age)
- return false ;
- if (name == null) {
- if (other.name != null)
- return false ;
- } else if (!name.equals(other.name))
- return false ;
- return true ;
- }
- }
- public class HashMapDemo{
- public static void main(String[] args){
- //将学生对象和学生的归属地通过键与值存储到map集合中
- HashMap<Student,String> hm = new HashMap<Student,String>();
- hm.put( new Student("lisi" ,38),"北京");
- hm.put( new Student("zhaoliu" ,24),"上海");
- hm.put( new Student("xiaoqiang" ,31),"沈阳");
- hm.put( new Student("wangcai" ,28),"大连");
- hm.put( new Student("zhaoliu" ,24),"铁岭");
-
- Iterator<Student> it = hm.keySet().iterator();
- while(it.hasNext()){
- Student key = it.next();
- String value = hm.get(key);
- System.out.println(key.getName() + ":" + key.getAge() + "---" + value);
- }
- }
- }
运行结果:
键有了判断依据,HashMap中的值就被覆盖。
示例6:
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.TreeMap;
- class ComparatorByName implements Comparator<Student>{
- public int compare(Student s1,Student s2){
- int temp = s1.getName().compareTo(s2.getName());
- return temp == 0?s1.getAge() - s2.getAge():temp;
- }
- }
- public class HashMapDemo{
- public static void main(String[] args){
- //将学生对象和学生的归属地通过键与值存储到map集合中
- TreeMap<Student,String> tm = new TreeMap<Student,String>(new ComparatorByName());
- tm.put( new Student("lisi" ,38),"北京");
- tm.put( new Student("zhaoliu" ,24),"上海");
- tm.put( new Student("xiaoqiang" ,31),"沈阳");
- tm.put( new Student("wangcai" ,28),"大连");
- tm.put( new Student("zhaoliu" ,24),"铁岭");
-
- Iterator<Map.Entry<Student,String>> it = tm.entrySet().iterator();
- while(it.hasNext()){
- Map.Entry<Student,String> me = it.next();
- Student key = me.getKey();
- String value = me.getValue();
- System.out.println(key.getName() + ":" + key.getAge() + "---" + value);
- }
- }
- }
使用LinkedHashMap则是跟原来存入的顺序是一致的。
示例7:
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.LinkedHashMap;
- import java.util.Map;
- public class LinkedHashMapDemo{
- public static void main(String[] args){
- HashMap<Integer,String> hm = new LinkedHashMap<Integer,String>();
- hm.put(7, "zhouqi");
- hm.put(3, "zhangsan");
- hm.put(1, "qianyi");
- hm.put(5, "wangwu");
- Iterator<Map.Entry<Integer,String>> it = hm.entrySet().iterator();
- while(it.hasNext()){
- Map.Entry<Integer,String> me = it.next();
- Integer key = me.getKey();
- String value = me.getValue();
- System.out. println(key + ":" + value);
- }
- }
- }
练习:
“fdqavcbsacdfs”获取该字符串中,每一个字母出现的次数。
要求打印结果是:a(2)b(1)...;
思路:
对于结果的分析发现,字母和次数之间存在着映射的关系,而且这种关系很多。
很多就需要存储,能存储映射关系的容器有数组和Map结合。
关系中没有编号!那就使用Map结合。
又发现可以保证唯一性的一方具备着顺序,如a、b、c...
所以可以使用TreeMap集合。
这个集合最终应该存储的是字母和次数的对应关系。
1. 因为操作的是字符串中的字母,所以先将字符串变成字符数组。
2. 遍历字符数组,用每一个字母作为键去查Map集合这个值。
如果该字母键不存在,就将该字母作为键,1作为值存储到map集合中。
如果该字母键存在,就将该字母键对应值取出并+1,再将该字母和+1后的值存储到map集合中。键相同值会覆盖,这样就记录住了该字母的次数。
3. 遍历结果,map集合就记录所有字母的出现的次数。
“fdqavcbsacdfs”获取该字符串中,每一个字母出现的次数。
要求打印结果是:a(2)b(1)...;
思路:
对于结果的分析发现,字母和次数之间存在着映射的关系,而且这种关系很多。
很多就需要存储,能存储映射关系的容器有数组和Map结合。
关系中没有编号!那就使用Map结合。
又发现可以保证唯一性的一方具备着顺序,如a、b、c...
所以可以使用TreeMap集合。
这个集合最终应该存储的是字母和次数的对应关系。
1. 因为操作的是字符串中的字母,所以先将字符串变成字符数组。
2. 遍历字符数组,用每一个字母作为键去查Map集合这个值。
如果该字母键不存在,就将该字母作为键,1作为值存储到map集合中。
如果该字母键存在,就将该字母键对应值取出并+1,再将该字母和+1后的值存储到map集合中。键相同值会覆盖,这样就记录住了该字母的次数。
3. 遍历结果,map集合就记录所有字母的出现的次数。
代码:
- import java.util.Iterator;
- import java.util.Map;
- import java.util.TreeMap;
- public class MapTest{
- public static void main(String[] args){
- String str = "fdqavcbsacdfs";
- String s = getCharCount(str);
- System.out.println(s);
- }
- public static String getCharCount(String str){
- //将字符串变为字符数组
- char[] chs = str.toCharArray();
-
- //定义map集合表
- Map<Character,Integer> map = new TreeMap<Character,Integer>();
-
- for(int i = 0; i < chs.length; i++){
- if(!(chs[i] >= 'a' && chs[i] <= 'z' || chs[i] >= 'A' && chs[i] <= 'Z' ))
- continue;
- //将数组中的字母作为键去查map表
- Integer value = map.get(chs[i]);
-
- int count = 0;
- //判断值是否为null
- if(value!=null){
- count = value;
- }
- count++;
- map.put(chs[i],count);
- }
- return mapToString(map);
- }
- private static String mapToString(Map<Character,Integer> map){
- StringBuilder sb = new StringBuilder();
- Iterator<Character> it = map.keySet().iterator();
- while(it.hasNext()){
- Character key = it.next();
- Integer value = map.get(key);
- sb.append(key + "(" + value + ")" );
- }
- return sb.toString();
- }
- }
Map在有映射关系时,可以优先考虑,在查表法中的应用较为多见。
示例:
- import java.util.HashMap;
- import java.util.Map;
- public class MapTest{
- public static void main(String[] args){
- String week = getWeek(1);
- System.out.println(week);
- System.out.println(getWeekByMap(week));
- }
- public static String getWeekByMap(String week){
- Map<String,String> map = new HashMap<String,String>();
-
- map.put( "星期一","Mon" );
- map.put( "星期二","Tue" );
- map.put( "星期三","Wes" );
- map.put( "星期日","Sun" );
- map.put( "星期天","Sun" );
-
- return map.get(week);
- }
- public static String getWeek(int week){
- if(week<1 || week>7)
- throw new RuntimeException("没有对应的星期,请您重新输入" );
- String[] weeks = { "","星期一" ,"星期二" };
-
- return weeks[week];
- }
- }
Collections工具类
Collections:是集合框架的工具类,里面的方法都是静态的。
Collections:是集合框架的工具类,里面的方法都是静态的。
示例1:
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- public class CollectionsDemo{
- public static void main(String[] args){
- demo1();
- }
- public static void demo1(){
- List<String> list = new ArrayList<String>();
- list.add( "abcde");
- list.add( "cba");
- list.add( "aa");
- list.add( "zzz");
- list.add( "cba");
- list.add( "nbaa");
- //对list集合进行指定顺序的排序
- Collections. sort(list);
- System. out.println(list);
- Collections. sort(list,new ComparatorByLength());
- System. out.println(list);
-
- mySort(list,new ComparatorByLength());
- System. out.println(list);
- }
- public static <T> void mySort(List<T> list,Comparator<? super T> comp){
- for(int i = 0; i < list.size() - 1; i++){
- for(int j = i + 1; j < list.size(); j++){
- if(comp.compare(list.get(i),list.get(j))>0){
- Collections. swap(list ,i,j);
- }
- }
- }
- }
- }
- class ComparatorByLength implements Comparator<String>{
- public int compare(String o1,String o2){
- int temp = o1.length() - o2.length();
- return temp == 0?o1.compareTo(o2):temp;
- }
- }
运行结果:
示例2:
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- public class CollectionsDemo{
- public static void main(String[] args){
- demo2();
- }
- public static void demo2(){
- List<String> list = new ArrayList<String>();
- list.add( "abcde");
- list.add( "cba");
- list.add( "aa");
- list.add( "zzz");
- list.add( "cba");
- list.add( "nbaa");
-
- Collections.sort(list);
- System.out.println(list);
- int index = Collections.binarySearch(list,"aaa");
- System.out.println( "index = " + index);//-2 -index-1
- //获取最大值
- String max = Collections.max(list, new ComparatorByLength());
- System.out.println( "max = " + max);
- }
- }
- class ComparatorByLength implements Comparator<String>{
- public int compare(String o1,String o2){
- int temp = o1.length() - o2.length();
- return temp == 0?o1.compareTo(o2):temp;
- }
- }
原因分析:
示例3:
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.TreeSet;
- public class CollectionsDemo{
- public static void main(String[] args){
- demo3();
- }
- public static void demo3(){
- TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder());
- ts = new TreeSet<String>(Collections.reverseOrder(new ComparatorByLength()));
- ts.add( "abc");
- ts.add( "hahaha");
- ts.add( "zzz");
- ts.add( "aa");
- ts.add( "cba");
- System.out.println(ts);
- }
- }
- class ComparatorByLength implements Comparator<String>{
- public int compare(String o1,String o2){
- int temp = o1.length() - o2.length();
- return temp == 0?o1.compareTo(o2):temp;
- }
- }
示例4:
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- public class CollectionsDemo{
- public static void main(String[] args){
- demo4();
- }
- public static void demo4(){
- List<String> list = new ArrayList<String>();
- list.add( "abcde");
- list.add( "cba");
- list.add( "aa");
- System. out.println(list);
- Collections. replaceAll(list,"cba", "nba");
- System. out.println(list);
- }
- }
示例5:
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- public class CollectionsDemo{
- public static void main(String[] args){
- demo5();
- }
- public static void demo5(){
- List<String> list = new ArrayList<String>();
- list.add( "abcde");
- list.add( "cba");
- list.add( "zhangsan");
- list.add( "zhaoliu");
- list.add( "xiaoqiang");
- System. out.println(list);
- Collections. shuffle(list);
- System. out.println(list);
- }
- }
原因分析:
0 0
- 黑马程序员——Java集合类
- 黑马程序员——java集合
- 黑马程序员——JAVA集合
- 黑马程序员——Java集合
- 黑马程序员——Java集合
- 黑马程序员——java集合
- 黑马程序员——Java基础---集合
- 【黑马程序员】 java笔记——集合
- 黑马程序员——Java集合框架
- 黑马程序员——Java基础---集合
- 黑马程序员——Java集合Collection
- 黑马程序员——java基础: 集合
- 黑马程序员——Java集合
- 黑马程序员——Java集合框架
- 黑马程序员——Java基础 ---集合
- 黑马程序员——Java集合
- 黑马程序员——Java基础---集合
- 黑马程序员——Java基础---集合
- linux基本命令-mysql命令
- model 键值对
- Principle of Computing(1)
- Android 4.4 AMS 学习笔记
- Linux内存管理
- 黑马程序员——JAVA集合
- 协议栈资料收集和大牛经验收集----阿冬!!!
- 归并排序的实现
- wpf下实现简单截图
- 线段树
- 【Android】进度条与线程之间的消息处理
- android dns解析
- 最小生成树
- SGU135 Drawing Lines