Java编程之Map中分拣思想。

简介: 题目:给定一个字符串,求出字符串中每一个单词在字符串中出现的次数 旨意:map的分拣思想。   每一个key的包装类,存放出现的次数 1 /** 2 * 作为包装类,用来存放英文单词,和该英文单词出现的次数 3 * @ClassName: Str 4 * @Descr...

题目:给定一个字符串,求出字符串中每一个单词在字符串中出现的次数

旨意:map的分拣思想。

 

每一个key的包装类,存放出现的次数

 1 /**
 2  * 作为包装类,用来存放英文单词,和该英文单词出现的次数
 3 * @ClassName: Str 
 4 * @Description: TODO(这里用一句话描述这个类的作用) 
 5 * @author 尚晓飞
 6 * @date 2014-7-30 下午6:57:29 
 7 *
 8  */
 9 public class Str {
10     private String st;
11     private int count;
12     public Str() {
13         super();
14     }
15     public String getSt() {
16         return st;
17     }
18     public void setSt(String st) {
19         this.st = st;
20     }
21     public int getCount() {
22         return count;
23     }
24     public void setCount(int count) {
25         this.count = count;
26     }
27 
28     
29 }
View Code

第一种分拣思想:(1)先为key创建对应的容器(2)使用容器,存放key对应的值

 

 1 /**
 2  * 字符串:this is a cat and that is a nice and where is the food
 3  * 将该字符串的每个单词出现的次数统计出来
 4  * 【分拣的思想】
 5  *  第一种:为所有key创建容器
 6  *        之后存放对应的value
 7  *  第二种:第一次创建容器,并存放value
 8  *       第二次之后,直接使用容器存放value
 9 * @ClassName: TestMap 
10 * @Description: TODO(这里用一句话描述这个类的作用) 
11 * @author 尚晓飞
12 * @date 2014-7-30 下午6:58:16 
13 *
14  */
15 public class TestMap {
16     
17     public static void main(String[] args) {
18         test4();
19         
20     }
21     
22     //第一种分拣思路 (1)先为所有的key创建对应的容器(2)为对应key的容器中存放值
23     public static void test1(){
24         String sts="this is a cat and that is a nice and where is the food";
25         //将字符串分割成一个个单词,并存放入数组中
26         String[] strings=sts.split(" ");
27         //创建一个map对象,用来存放单词和单词出现的次数
28         Map<String, Str> countMap=new HashMap<String, Str>();
29         //第一种分拣思想
30         //第一步:为所有的key创建容器,
31         for(int i=0;i<strings.length;i++){
32             String temp=strings[i];
33             //判断map是否含有此key,如果有返回true,否则返回false
34             //第一次为所有的key创建容器
35             if(!countMap.containsKey(temp)){
36                 Str str=new Str();
37                 countMap.put(temp, str);
38             }
39         }
40         
41         //第二步:使用容器,存放值
42         for(String temp:strings){
43             Str clsStr=countMap.get(temp);
44             clsStr.setCount(clsStr.getCount()+1);
45             clsStr.setSt(temp);
46         }
47         
48         
49         //测试countMap是否算是成功达到目的
50         Set<String> keys=countMap.keySet();
51         for (String key:keys) {
52             Str sd=countMap.get(key);
53             Integer cInteger=sd.getCount();
54             System.out.println("字母:"+key+"--次数:"+cInteger);
55         }
56         
57     }
58     //第一种分拣思路 (1)先为所有的key创建对应的容器(2)为对应key的容器中存放值
59     public static void test2(){
60         String sts="this is a cat and that is a nice and where is the food";
61         //将字符串分割成一个个单词,并存放入数组中
62         String[] strings=sts.split(" ");
63         //创建一个map对象,用来存放单词和单词出现的次数
64         Map<String, Str> countMap=new HashMap<String, Str>();
65         //第一种分拣思想
66         //第一步:为key创建容器的同时,并存放值
67         for(int i=0;i<strings.length;i++){
68             String temp=strings[i];
69             //判断map是否含有此key,如果有返回true,否则返回false
70             //先创建容器,之后为容器存放值
71             if(!countMap.containsKey(temp)){
72                 Str str=new Str();
73                 countMap.put(temp, str);
74             }
75                 //使用容器存放值
76                 Str str=countMap.get(temp);
77                 str.setCount(str.getCount()+1);
78             
79         }
80         
81         //测试countMap是否算是成功达到目的
82                 Set<String> keys=countMap.keySet();
83                 for (String key:keys) {
84                     Str sd=countMap.get(key);
85                     Integer cInteger=sd.getCount();
86                     System.out.println("字母:"+key+"--次数:"+cInteger);
87                 }
88     }
89 
90 }
View Code

 

第二种分拣思想:(1)第一次为key创建容器,并存key对应的值(2)第二次使用创建好的容器,存放key对应的值

 

 1  * 【分拣的思想】
 2  *  第一种:为所有key创建容器
 3  *        之后存放对应的value
 4  *  第二种:第一次创建容器,并存放value
 5  *       第二次之后,直接使用容器存放value
 6 * @ClassName: TestMap 
 7 * @Description: TODO(这里用一句话描述这个类的作用) 
 8 * @author 尚晓飞
 9 * @date 2014-7-30 下午6:58:16 
10 *
11  */
12 public class TestMap {
13     
14     public static void main(String[] args) {
15         test4();
16         
17     }
18     
19     
20     
21     //分拣第二种思想 (1)第一次为key创建容器,并存放值(2)第二次使用容器存放值
22     public static void test3(){
23         String sts="this is a cat and that is a nice and where is the food";
24         //将字符串分割成一个个单词,并存放入数组中
25         String[] strings=sts.split(" ");
26         //创建一个map对象,用来存放单词和单词出现的次数
27         Map<String, Str> countMap=new HashMap<String, Str>();
28         //第一种分拣思想
29         //第一步:为key创建容器的同时,并存放值
30         for(int i=0;i<strings.length;i++){
31             String temp=strings[i];
32             //判断map是否含有此key,如果有返回true,否则返回false
33             //第一次创建容器,并为容器中存放值
34             if(!countMap.containsKey(temp)){
35                 Str str=new Str();
36                 str.setCount(1);
37                 countMap.put(temp, str);
38             }else{
39                 //第二次使用容器存放值
40                 Str str=countMap.get(temp);
41                 str.setCount(str.getCount()+1);
42             }
43         }
44         
45         //测试countMap是否算是成功达到目的
46                 Set<String> keys=countMap.keySet();
47                 for (String key:keys) {
48                     Str sd=countMap.get(key);
49                     Integer cInteger=sd.getCount();
50                     System.out.println("字母:"+key+"--次数:"+cInteger);
51                 }
52     }
53     
54     
55     //第二种分拣思路:(1)第一次为key创建容器,并存放值(2)第二次使用容器存放值
56     public static void test4(){
57         String sts="this is a cat and that is a nice and where is the food";
58         //将字符串分割成一个个单词,并存放入数组中
59         String[] strings=sts.split(" ");
60         //创建一个map对象,用来存放单词和单词出现的次数
61         Map<String, Str> countMap=new HashMap<String, Str>();
62         //第一种分拣思想
63         //第一步:为key创建容器的同时,并存放值
64         for(int i=0;i<strings.length;i++){
65             String temp=strings[i];
66             //判断map是否含有此key,如果有返回true,否则返回false
67             //第一次创建容器,并为容器中存放值
68             Str str=null;
69             if(null==(str=countMap.get(temp))){
70                  str=new Str();
71                 str.setCount(1);
72                 countMap.put(temp, str);
73             }else{
74                 //第二次使用容器存放值
75                  str=countMap.get(temp);
76                 str.setCount(str.getCount()+1);
77             }
78         }
79         
80         //测试countMap是否算是成功达到目的
81                 Set<String> keys=countMap.keySet();
82                 for (String key:keys) {
83                     Str sd=countMap.get(key);
84                     Integer cInteger=sd.getCount();
85                     System.out.println("字母:"+key+"--次数:"+cInteger);
86                 }
87     }
88 }
View Code

 

 

分拣思想的应用:

 需求:查询出学生List集合,对学生集合进行加工,将学生按照班级分类,并求出班级的总分和平均分

 思路:map分拣思想。需要创建一个班级po,班级po里存放学生信息,该班集的总分,班级号码。

Student的po

 1 /**
 2  * 学生对象
 3 * @ClassName: Student 
 4 * @Description: TODO(这里用一句话描述这个类的作用) 
 5 * @author 尚晓飞
 6 * @date 2014-7-31 下午6:16:39 
 7 *
 8  */
 9 public class Student {
10     private String name;//姓名
11     private String no;//班级
12     private Integer score;//分数
13     
14     
15     public Student() {
16         super();
17     }
18     
19     public Student(String name, String no, Integer score) {
20         super();
21         this.name = name;
22         this.no = no;
23         this.score = score;
24     }
25 
26 
27     public String getName() {
28         return name;
29     }
30     public void setName(String name) {
31         this.name = name;
32     }
33     public String getNo() {
34         return no;
35     }
36     public void setNo(String no) {
37         this.no = no;
38     }
39     public Integer getScore() {
40         return score;
41     }
42     public void setScore(Integer score) {
43         this.score = score;
44     }
45     
46     
47 }
View Code

需要进行存放学生信息的ClassRoom的po

 1 package com.bjsxt.xiaofei;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 public class ClassRoom {
 7     private String no;//班级号码
 8     private Set<Student> students;//班级里的学生
 9     private Integer countScore;//总分
10     
11     public ClassRoom(){
12         students=new HashSet<Student>();
13     }
14     
15     public ClassRoom(String no, Integer countScore) {
16         this();
17         this.no = no;
18         this.countScore = countScore;
19     }
20 
21     public String getNo() {
22         return no;
23     }
24 
25     public void setNo(String no) {
26         this.no = no;
27     }
28 
29     public Set<Student> getStudents() {
30         return students;
31     }
32 
33     public void setStudents(Set<Student> students) {
34         this.students = students;
35     }
36 
37     public Integer getCountScore() {
38         return countScore;
39     }
40 
41     public void setCountScore(Integer countScore) {
42         this.countScore = countScore;
43     }
44     
45     
46 }
View Code

加工学生list集合,并进行测试

package com.bjsxt.xiaofei;

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

/**
 * 从学生表里查询出一个学生集合,现在求出每个班级的成绩总分,和平均分。
 * 利用Map的分拣思想,做到。
* @ClassName: Test2 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author 尚晓飞
* @date 2014-8-1 上午8:47:24 
*
 */
public class Test2 {
    public static void main(String[] args) {
        //获取学生集合
        List<Student> studentList=queryAll();
        //加工学生集合。返回一个map.map里装的是key:【班级号】 value:【classRoom】
        Map<String,ClassRoom> classMap=processStList(studentList);
        //测试Map
        testMap(classMap);
    }
    
    //获得学生集合
    public static List<Student> queryAll(){
        List<Student> list=new ArrayList<Student>();
        list.add(new Student("a", "一班", 80));
        list.add(new Student("b", "二班", 100));
        list.add(new Student("c", "三班", 60));
        list.add(new Student("d", "一班", 80));
        list.add(new Student("e", "二班", 100));
        list.add(new Student("f", "三班", 60));
        return list;
    }
    
    //加工学生集合,返回Map
    public static  Map<String, ClassRoom> processStList(List<Student> studentList){
        //生成一个map
        Map<String, ClassRoom> classMap=new HashMap<String, ClassRoom>();
        
        //遍历学生集合
        for(Student st:studentList){
            //获取当前学生的班级号码,和成绩
            String classNum=st.getNo();
            Integer score=st.getScore();
            //如果map中不含该学生的班级号,则为该学生创建新班级对象,并将该学生信息存入其中
            if(!classMap.containsKey(classNum)){
                //创建班级
                ClassRoom cls=new ClassRoom();
                //将班级号和班级作为映射关系,存放入classMap
                classMap.put(classNum, cls);
                //将当前此学生的信息存入班级中
                cls.setCountScore(score);
                Set<Student> set=cls.getStudents();
                set.add(st);
                
            }else{
                //通过存在的班级号,往里存放当前学生
                ClassRoom cls=classMap.get(classNum);
                cls.setCountScore(cls.getCountScore()+score);
                Set<Student> set=cls.getStudents();
                set.add(st);
            }            
            
            
        }
        
        return classMap;
    }
    
    
    
    public static void testMap(Map<String, ClassRoom> classMap){
        //遍历map
        Set<String> set=classMap.keySet();
        //遍历set中的map键
        for (String key : set) {
            //班级
            ClassRoom cls=classMap.get(key);
            //打印要求的信息
            System.out.println("班级号码:"+key+"   班级总分:"+cls.getCountScore()+"   班级平均分"+cls.getCountScore()/cls.getStudents().size());
        }
        
    }
}
View Code

 第二种测试里,展现了另一种map的遍历方法和set集合的三种遍历方法

 

 1 public static void testMap(Map<String, ClassRoom> classMap){
 2         //第二种遍历Map。将Map装换成set集合,set集合里的每一个对象是map的映射关系新组成的一个Map.Entry的对象。通过getkey() getvalue()方法获取KEY-VALUE的映射
 3         Set<Map.Entry<String,ClassRoom>> setEntry=classMap.entrySet();
 4         
 5         //第一种遍历set集合  将set集合转换成数组
 6         Object[] objects=setEntry.toArray();
 7         for(int i=0;i<objects.length;i++){
 8             Map.Entry<String, ClassRoom> entyr=(Entry<String, ClassRoom>) objects[i];
 9             String classNum=entyr.getKey();
10             ClassRoom cls=entyr.getValue();
11             System.out.println("普通for班级号码:"+classNum+"----班级总分:"+cls.getCountScore()+"----班级平均分"+cls.getCountScore()/cls.getStudents().size());
12             
13         }
14         
15         //第二种遍历set集合 增强for循环
16         for(Map.Entry<String, ClassRoom> entry:setEntry){
17             
18             String classNum=entry.getKey();
19             ClassRoom cls=entry.getValue();
20             System.out.println("班级号码:"+classNum+"----班级总分:"+cls.getCountScore()+"----班级平均分"+cls.getCountScore()/cls.getStudents().size());
21         }
22         
23         //第三种遍历set集合:利用迭代器遍历Set集合
24         Iterator<Map.Entry<String, ClassRoom>> iterator=setEntry.iterator();
25         while (iterator.hasNext()) {
26             Map.Entry<String, ClassRoom> entry=iterator.next();
27             String classNum=entry.getKey();
28             ClassRoom cls=entry.getValue();
29             System.out.println("班级号码:"+classNum+"----班级总分:"+cls.getCountScore()+"----班级平均分"+cls.getCountScore()/cls.getStudents().size());
30             
31         }
32     }
View Code

 

相关文章
|
1天前
|
安全 Java
深入理解Java并发编程:线程安全与性能优化
【5月更文挑战第11天】在Java并发编程中,线程安全和性能优化是两个重要的主题。本文将深入探讨这两个方面,包括线程安全的基本概念,如何实现线程安全,以及如何在保证线程安全的同时进行性能优化。我们将通过实例和代码片段来说明这些概念和技术。
2 0
|
1天前
|
Java 调度
Java并发编程:深入理解线程池
【5月更文挑战第11天】本文将深入探讨Java中的线程池,包括其基本概念、工作原理以及如何使用。我们将通过实例来解释线程池的优点,如提高性能和资源利用率,以及如何避免常见的并发问题。我们还将讨论Java中线程池的实现,包括Executor框架和ThreadPoolExecutor类,并展示如何创建和管理线程池。最后,我们将讨论线程池的一些高级特性,如任务调度、线程优先级和异常处理。
|
2天前
|
存储 安全 Java
Java一分钟之-Map接口与HashMap详解
【5月更文挑战第10天】Java集合框架中的`Map`接口用于存储唯一键值对,而`HashMap`是其快速实现,基于哈希表支持高效查找、添加和删除。本文介绍了`Map`的核心方法,如`put`、`get`和`remove`,以及`HashMap`的特性:快速访问、无序和非线程安全。讨论了键的唯一性、`equals()`和`hashCode()`的正确实现以及线程安全问题。通过示例展示了基本操作和自定义键的使用,强调理解这些概念对编写健壮代码的重要性。
5 0
|
2天前
|
存储 Java
【JAVA基础篇教学】第十篇:Java中Map详解说明
【JAVA基础篇教学】第十篇:Java中Map详解说明
|
2天前
|
缓存 Java 数据库
Java并发编程学习11-任务执行演示
【5月更文挑战第4天】本篇将结合任务执行和 Executor 框架的基础知识,演示一些不同版本的任务执行Demo,并且每个版本都实现了不同程度的并发性。
20 4
Java并发编程学习11-任务执行演示
|
2天前
|
存储 安全 Java
Java容器类List、ArrayList、Vector及map、HashTable、HashMap
Java容器类List、ArrayList、Vector及map、HashTable、HashMap
|
3天前
|
存储 安全 Java
12条通用编程原则✨全面提升Java编码规范性、可读性及性能表现
12条通用编程原则✨全面提升Java编码规范性、可读性及性能表现
|
3天前
|
缓存 Java 程序员
关于创建、销毁对象⭐Java程序员需要掌握的8个编程好习惯
关于创建、销毁对象⭐Java程序员需要掌握的8个编程好习惯
关于创建、销毁对象⭐Java程序员需要掌握的8个编程好习惯
|
3天前
|
缓存 Java 数据库
Java并发编程中的锁优化策略
【5月更文挑战第9天】 在高负载的多线程应用中,Java并发编程的高效性至关重要。本文将探讨几种常见的锁优化技术,旨在提高Java应用程序在并发环境下的性能。我们将从基本的synchronized关键字开始,逐步深入到更高效的Lock接口实现,以及Java 6引入的java.util.concurrent包中的高级工具类。文中还会介绍读写锁(ReadWriteLock)的概念和实现原理,并通过对比分析各自的优势和适用场景,为开发者提供实用的锁优化策略。
4 0
|
4天前
|
JavaScript 小程序 Java
基于java的少儿编程网上报名系统
基于java的少儿编程网上报名系统
11 2