集合

定义

集合是用来存储数据的,也是数据的一种容器,集合只能去存储对象,每个对象就是集合中的一个元素

数组和集合之间的区别:

1.数组长度固定,数组只能存储同一种数据类型,但是数组是能存基本数据类型(四类八种)和引用数据类型(引用:对象引用的地址;数组,类,接口)。
2.集合长度不固定,它不用声明具体长度,因为集合可以自动扩容,集合只能去存储对象(引用数据类型),集合中存储的数字是int 类型的包装类。
集合可以存储多种数据类型: list("hello", 123, Student)
注意:真是项目中集合中通常只存同一种数据类型

集合的语法:

集合是存在方法java.util包下
共同的接口:collection接口
map集合:
也可以去存放数据,map集合存放数据的方式是通过键值对的方式来存放的。
键:key
值:value.
可以通过key快速查找到具体的value值
将123存入map
<key, value>
注意:如果list集合在不加泛型的情况下,默认的类型为object类型。
泛型:如果一个集合添加泛型,此集合就只能存储泛型中的数据类型
泛型语法: list<数据类型>

list集合中arraylist语法:

  • 创建集合:
import java.util.ArrayList;
import java.util.List;

public class Practice {
    public static void main(String[] args) {
//面向接口
        List list = new ArrayList();
//面向实现类
//      ArrayList list2 = new Arraylist();
        list.add("haha");
        list.add(123);
        list.add(12.34);
        System.out.println(list);
        //加泛型集合
        List<Integer> list2 = new ArrayList<>();
        list2.add(123);
        list2.add(432);
        list2.add(1,567);
//如果当前位置有数据,当前位置的数据自动向后移动一位
        System.out.println(list2);
        list2.addAll(list);//参数中加入的是集合对象
        System.out.println(list2);
    }
}

[haha, 123, 12.34]
[123, 567, 432]
[123, 567, 432, haha, 123, 12.34]

Process finished with exit code 0

list2.addAll(list);
参数中加入的是集合对象
list.size();
返回此列表中的元素数

集合中add方法和addAll的区别

add方法; 向集合中插入一个元素,如果此元素有多条数据,这些数据共享一个下标。
addAll:先将对象中的数据一个一个拿出来,分别存入集合当中(传入的对象中有多少个元素就占多少个下标)
注意:addAll(集合对象)

contains();
如果此列表中包含此元素,则返回true。此方法参数为object类型,可以传入对象和具体的数据。

get();
访问集合中具体的元素索引值

集合的遍历:

for (int i = 0; i < list.size(); i++){
  System.out.println(list.get(i));
}
List<String> stringList = new ArrayList<>();
for(String string : stringList){
  System.out.println(string);
}

ArrayList自动扩容:
list集合底层还是用数组来实现的首先:当我们创建一个数组时,其长度是我们手动设置的,但是在list集合中,在创建一个集合时:默认开辟一个长度为10的集合空间, List list = new ArrayList();,
如果此空间存放满了, jvm会在原来空间的基础上*1.5倍自动进行扩容。

list集合的特点:list是一种线性集合。

likedlist:底层也使用数组来实现的,它的实现方式是通过链表来实现的

ArrayList特点:访问快但是插入删除慢
Linkedlist特点: 访问慢但是插入删除块, 是有序(按照存入的顺序排序,集合中显示的顺序就是存入的顺序)可重复(可以有重复的数据)的集合。

LinkedList语法和ArrayList语法一样
List list = new LinkedList();
List list = new ArrayList();

public class Practice {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List list = new ArrayList();
        while (true){
            System.out.println("请输入狗的名字,no退出");
            String input = scanner.nextLine();
            if (input.equals("no")){
                for (int i = 0; i < list.size(); i++) {
                    System.out.println(list.get(i));
                }
                System.out.println("退出了");
                break;
            }
            else {
                list.add(input);
            }
        }
    }
}

set接口(集合):

无序(不按照存入顺序排序)不重复(set集合中不允许有重复的数据)集合

Map接口(集合):

Map<key,value> or Map<Entry>
Entry使其可以看成特殊List
Map的Key不能重复
key:int,String
get(Key):输出Value
Ex:

Map<String, String> map = new HashMap<>();
map.put("阴","阳的对立面");
String strValue = map.get("阴"); 
System.out.println(strValue);
——>阳的对立面

是否包含某个key:
map.containsKey("道");

public class Practice {
    public static void main(String[] args) {
       Map<String,String> map = new HashMap<>();
       map.put("a","letter");
       map.put("hello world","sentence");
        System.out.println("请输入要查找的字");
        Scanner scanner = new Scanner(System.in);
        String word = scanner.nextLine();
        if (map.containsKey(word)){
            String string = map.get(word);
            //删除
            map.remove(word);
            System.out.println(string);
        }
        else{
            System.out.println("not found"+word);
        }
    }
}

Map遍历:

for (String strTemp : map.keySet()){
            System.out.println(strTemp);//Key
            System.out.println(map.get(strTemp));//Value
        }
for (Map.Entry entry : map.entrySet()){
            System.out.println(entry.getKey());//Key
            System.out.println(entry.getValue());//Value
        }
System.out.println("请输入一串字: ");
        Scanner scanner = new Scanner(System.in);
        String string = scanner.nextLine();
        String[] str = string.split(" ");
        Map<String,Integer> map = new HashMap<>();
        for (int i = 0; i < str.length; i++){
            if (map.containsKey(str[i])) {
                Integer count = map.get(str[i]);
                map.put(str[i], ++count);

            }
            else {
                map.put(str[i],1);
            }
        }
        for (Map.Entry entry : map.entrySet()){
            System.out.println(entry);
        }

请输入一串字: 
a b a b a
a=3
b=2
package com.company;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ttc on 2018/6/1.
 */
public class WordCount {
    public static void main(String[] args) {
        // 程序 = 数据结构 + 算法
        String strTemp = "this is a dog that is a desk long long ago there is a girl";
        String[] strArrays = strTemp.split(" ");
        System.out.println(Arrays.toString(strArrays));
        Map<String,Integer> map = new HashMap<>();
        //把单词在字符串数组中保存转换为在map中保存
        for(String strWord : strArrays)
        {
            //去map中考察,看map的key的集合中是否包含该单词
            //如果不包含,往map中添加一个元素,key是单词,值是1
            if(!map.containsKey(strWord))
            {
                map.put(strWord,1);
            }
            //如果包含,从map中通过该key取到对应的值(该单词之前已经出现过的次数)
            //把这个值加1,在存回去
            else
            {
                Integer count = map.get(strWord);
                count++;
                map.put(strWord,count);
            }
        }

        for(Map.Entry entry : map.entrySet())
        {
            System.out.println(entry);
        }

    }
}


Map<Integer,String> year2country = new HashMap<>();
        year2country.put(1930,"乌拉圭");
        year2country.put(1934,"意大利");
        year2country.put(1938,"意大利");
        year2country.put(1950,"乌拉圭");
        year2country.put(1954,"西德");
        year2country.put(1958,"巴西");
        year2country.put(1962,"巴西");
        year2country.put(1966,"英格兰");
        year2country.put(1970,"巴西");
        year2country.put(1974,"西德");
        year2country.put(1978,"阿根廷");
        year2country.put(1982,"意大利");
        year2country.put(1986,"阿根廷");
        year2country.put(1990,"西德");
        year2country.put(1994,"巴西");
        year2country.put(1998,"法国");
        year2country.put(2002,"巴西");
        year2country.put(2006,"意大利");
        year2country.put(2010,"西班牙");
        year2country.put(2014,"德国");

        Scanner scanner = new Scanner(System.in);
System.out.println("请输入要查询的国家:");
 String country = scanner.nextLine();
        for(Map.Entry entry : year2country.entrySet())
        {
            if (entry.getValue().equals(country)){
                System.out.println(entry.getKey());
}
        }
        if (!year2country.containsValue(country)){
            System.out.println(country+"没有获得过世界杯");
        }

在这个list 的基础上,完成下列要求:

1) 计算所有学生的平均年龄

2) 计算各个班级的平均分


image.png
package com.company;

/**
 * Created by ttc on 2018/6/4.
 */
public class Student {
    private String name;

    private int age;

    private int score;

    private String classNum;

    public Student(String name, int age, int score, String classNum) {
        this.name = name;
        this.age = age;
        this.score = score;
        this.classNum = classNum;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getClassNum() {
        return classNum;
    }

    public void setClassNum(String classNum) {
        this.classNum = classNum;
    }

}

package com.company;

import jdk.internal.util.xml.impl.Input;

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

/**
 * Created by ttc on 2018/6/4.
 */
public class TestStudents {
    public static void main(String[] args) {
        List<Student> list = new ArrayList();

        list.add(new Student("Tom", 18, 100, "class05"));
        list.add(new Student("Jerry", 22, 70, "class04"));
        list.add(new Student("Owen", 25, 90, "class05"));
        list.add(new Student("Jim", 30,80 , "class05"));
        list.add(new Student("Steve", 28, 66, "class06"));
        list.add(new Student("Kevin", 24, 100, "class04"));

        //每个班级的学生成绩列表
        Map<String,List<Integer>> mapClass2Scores = new HashMap<>();
//        [class04:(70,100);class05:(100,90,80);class06:(66)];

        for(Student student : list)
        {
            if(mapClass2Scores.containsKey(student.getClassNum()))
            {

                //拿到当前班级的学生成绩列表对象
                List<Integer> lst = mapClass2Scores.get(student.getClassNum());
                lst.add(student.getScore());

            }
            else//该学生所在班级,第一次加入到map中
            {
                List<Integer> lst = new ArrayList<>();
                lst.add(student.getScore());
                mapClass2Scores.put(student.getClassNum(),lst);
            }
        }

        for(Map.Entry entry : mapClass2Scores.entrySet())
        {
            System.out.println("班级:" + entry.getKey());
            List<Integer> listScores = (List<Integer>)entry.getValue();
            int sum = 0;
            for(Integer score : listScores)
            {
                sum += score;
            }

            System.out.println(sum/listScores.size());

        }


        int age_sum = 0;
        for(Student student : list)
        {
            age_sum += student.getAge();
        }
        System.out.println(age_sum/list.size());



    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,064评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,606评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,011评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,550评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,465评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,919评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,428评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,075评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,208评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,185评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,191评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,914评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,482评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,585评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,825评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,194评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,703评论 2 339

推荐阅读更多精彩内容