Java常用工具——java集合

一、ArrayList

package com.imooc.set;

import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo {

    public static void main(String[] args) {
        // 用ArrayList存储编程语言的名称,并输出。
        //名称包括”Java”、”C”、”C++“、”Go”和”Swift”
        List list=new ArrayList();
        list.add("Java");
        list.add("C");
        list.add("C++");
        list.add("Go");
        list.add("Swift");
        //输出列表中元素的个数
        System.out.println("列表中元素的个数:"+list.size());
        
        //遍历输出所有编程语言
        System.out.println("==========================");
        for(int i=0;i<list.size();i++) {
            System.out.print(list.get(i)+" ");
        }
        System.out.println();

        //移除列表中的C++
        System.out.println("==========================");
//        list.remove(2);
        list.remove("C++");
        System.out.println("移除c++后列表的元素为:");
        for(int i=0;i<list.size();i++) {
            System.out.print(list.get(i)+" ");
        }
        System.out.println();
    }

}

二、案例

  • 需求

-公告的添加和显示

-在指定位置处插入公告

-删除公告

-修改公告

  • 公告类属性

-编号 id

 - 标题 title

-创建人 creator

-创建时间 createTime

  • 公告类方法

-构造方法

-获取和设置属性值的方法

package com.imooc.set;

import java.util.Date;

public class Notice {
    //Notice类,属性:id,title,creator,ctreaterDate
    private int id;
    private String title;
    private String creator;
    private Date creatTime;
    //构造方法
    public Notice(int id, String title, String creator, Date creatTime) {
        super();
        this.id = id;
        this.title = title;
        this.creator = creator;
        this.creatTime = creatTime;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    public Date getCreatTime() {
        return creatTime;
    }
    public void setCreatTime(Date creatTime) {
        this.creatTime = creatTime;
    }
    
    
    
    
}
package com.imooc.set;

import java.util.ArrayList;
import java.util.Date;


public class NoticeTest {

    public static void main(String[] args) {
        // 创建Notice类的对象,生成三条公告
        Notice notice1=new Notice(1,"欢迎来到java世界!","管理员",new Date());
        Notice notice2=new Notice(2,"请按时提交作业","老师",new Date());
        Notice notice3=new Notice(3,"考勤通知","老师",new Date());
        //添加公告
        ArrayList noticeList=new ArrayList();
        noticeList.add(notice1);
        noticeList.add(notice2);
        noticeList.add(notice3);
        //显示公告
        System.out.println("公告内容为:");
        for(int i=0;i<noticeList.size();i++) {
            System.out.println(i+1+":"+((Notice)noticeList.get(i)).getTitle());
        }
    }

}

3、删除、修改公告

package com.imooc.set;

import java.util.ArrayList;
import java.util.Date;


public class NoticeTest {
    
    public static void main(String[] args) {
        // 创建Notice类的对象,生成三条公告
        Notice notice1=new Notice(1,"欢迎来到java世界!","管理员",new Date());
        Notice notice2=new Notice(2,"请按时提交作业","老师",new Date());
        Notice notice3=new Notice(3,"考勤通知","老师",new Date());
        //添加公告
        ArrayList noticeList=new ArrayList();
        noticeList.add(notice1);
        noticeList.add(notice2);
        noticeList.add(notice3);
        //显示公告
        System.out.println("公告内容为:");
        for(int i=0;i<noticeList.size();i++) {
            System.out.println(i+1+":"+((Notice)noticeList.get(i)).getTitle());
        }
        //再第二条位置新增一条公告
        Notice notice4=new Notice(4,"在线编辑器可以使用了","管理员",new Date());
        noticeList.add(1,notice4);
        //显示公告
        System.out.println("======================");
        System.out.println("公告内容为:");
        for(int i=0;i<noticeList.size();i++) {
            System.out.println(i+1+":"+((Notice)noticeList.get(i)).getTitle());
        }
        //删除按时提交作业的公告
        noticeList.remove(2);
        //显示公告
        System.out.println("======================");
        System.out.println("公告内容为:");
        for(int i=0;i<noticeList.size();i++) {
            System.out.println(i+1+":"+((Notice)noticeList.get(i)).getTitle());
        }
        //修改第二条公告的title
        notice4.setTitle("JAVA在线编辑器可以使用了!");
        noticeList.set(1,notice4);
        //显示公告
        System.out.println("======================");
        System.out.println("公告内容为:");
        for(int i=0;i<noticeList.size();i++) {
            System.out.println(i+1+":"+((Notice)noticeList.get(i)).getTitle());
        }
    }

}

 四、HashSet

常用方法

package com.imooc.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CatTest {

    public static void main(String[] args) {
        // 定义宠物猫对象
        Cat huahua=new Cat("花花",12,"英国短毛猫");
        Cat fanfan=new Cat("凡凡",3,"中华田园猫");
        //将宠物猫对象放入HashSet中
        Set set=new HashSet();
        set.add(huahua);
        set.add(fanfan);
        //显示宠物猫信息
        Iterator it=set.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }
        //再添加一个与花花属性一样的猫
        Cat huahua1=new Cat("花花",12,"英国短毛猫");
        set.add(huahua1);
        System.out.println("=================================");
        System.out.println("添加重复数据后的宠物猫信息为:");
        //显示宠物猫信息
        it=set.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }
    }

}
package com.imooc.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/*
 * 查找
 * 1、在集合中查找花花的信息并输出
 * 2、通过名字查找花花的信息
 */

public class CatTest2 {

    public static void main(String[] args) {
        //创建宠物猫对象
        Cat huahua=new Cat("花花",12,"英国短毛猫");
        Cat huahua02=new Cat("花花二代",2,"英国短毛猫");
        Cat fanfan=new Cat("凡凡",612,"中华田园猫");
        //将宠物猫对象放到set中.add()
        Set set=new HashSet();
        set.add(huahua);
        set.add(huahua02);
        set.add(fanfan);
        
        
        //1、在集合中查找花花的信息并输出.contains()
        if(set.contains(huahua)) {
            System.out.println("花花找到了!");
            System.out.println(huahua);
        }else {
            System.out.println("花花没有找到!");
        }
        
        //2、通过名字查找花花的信息
        boolean flag=false;
        Cat c=null;
        Iterator it=set.iterator();
        while(it.hasNext()){
            c=(Cat)it.next();
            if(c.getName().equals("花花")) {
                flag=true;
                break;
            }
        }
        if(flag) {
            System.out.println("花花找到了");
            System.out.println(c);
        }else {
            System.out.println("花花没有找到");
        }
    }

}
package com.imooc.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/*
 * 查找
 * 1、在集合中查找花花的信息并输出
 * 2、通过名字查找花花的信息
 */

public class CatTest2 {

    public static void main(String[] args) {
        //创建宠物猫对象
        Cat huahua=new Cat("花花",12,"英国短毛猫");
        Cat huahua02=new Cat("花花二代",2,"英国短毛猫");
        Cat fanfan=new Cat("凡凡",3,"中华田园猫");
        //将宠物猫对象放到set中.add()
        Set<Cat> set=new HashSet<Cat>();
        set.add(huahua);
        set.add(huahua02);
        set.add(fanfan);
        
        
        //1、在集合中查找花花的信息并输出.contains()
        if(set.contains(huahua)) {
            System.out.println("花花找到了!");
            System.out.println(huahua);
        }else {
            System.out.println("花花没有找到!");
        }
        
        //2、通过名字查找花花的信息
        boolean flag=false;
        Cat c=null;
        Iterator<Cat> it=set.iterator();
        while(it.hasNext()){
            c=(Cat)it.next();
            if(c.getName().equals("花花")) {
                flag=true;
                break;
            }
        }
        if(flag) {
            System.out.println("花花找到了");
            System.out.println(c);
        }else {
            System.out.println("花花没有找到");
        }
    
    //删除花花二代的信息并重写输出
//    for(Cat cat:set) {
//        if(cat.getName().equals("花花二代")) {
//            set.remove(cat);
//            break;
//        }
//    }
    Set<Cat> set1=new HashSet<Cat>();
    for(Cat cat:set) {
        if(cat.getMonth()<5) {
            set1.add(cat);
        }
    }
    set.removeAll(set1);
    System.out.println("=================================");
    System.out.println("删除花花二代后的宠物猫信息为:");
    //显示宠物猫信息
    it=set.iterator();
    while(it.hasNext()) {
        System.out.println(it.next());
    }
    //删除集合中所有宠物猫信息
    System.out.println("=================================");
//    boolean flag1=set.removeAll(set);
//    if(flag1) {
    set.removeAll(set);
    if(set.isEmpty()) {
        System.out.println("猫都不见了!");
    }else {
        System.out.println("猫还在~~");
    }
    }
}

五、Map

Map
• Map中的数据是以键值对(key-value)的形式存储的
• key-value以Entry类型的对象实例存在
• 可以通过key值快速地查找value
• 一个映射不能包含重复的键
• 每个键最多只能映射到一个值
 
HashMap
• 基于哈希表的Map接口的实现
• 允许使用null值和null键
• key值不允许重复
• HashMap中的Entry对象是无序排列的
 
案例1
• 完成一个类似字典的功能。
- 将单词以及单词的注释存储到HashMap中
- 显示HashMap中的内容
- 查找某个单词的注释并显示
 
package com.imooc.set;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

/*
 * 案例1
• 完成一个类似字典的功能。
- 将单词以及单词的注释存储到HashMap中
- 显示HashMap中的内容
- 查找某个单词的注释并显示
 */
public class DictionDemo {
    public static void main(String[] args) {
        Map<String,String> animal=new HashMap<String,String>();
        System.out.println("请输入三组单词对应的注释,并存放到HashMap中:");
        Scanner sc=new Scanner(System.in);
        //添加数据
        for(int i=0;i<3;i++) {
            System.out.println("请输入key的值:");
            String key=sc.next();
            System.out.println("请输入value的值:");
            String value=sc.next();
            animal.put(key,value);
        }
        //打印并输出value的值(直接使用迭代器)
        System.out.println("======================");
        System.out.println("使用迭代器输出所有value:");
        Iterator<String> it=animal.values().iterator();
        while(it.hasNext()) {
            System.out.print(it.next()+" ");
        }
        System.out.println();
        System.out.println("======================");
        //打印并输出key-value的值(直接entrySet)
        System.out.println("通过entrySet方法获得key-value:");
        Set<Entry<String, String>> entrySet=animal.entrySet();
        for(Entry<String, String> entry:entrySet) {
            System.out.print(entry.getKey()+"-");
            System.out.println(entry.getValue());
        }
    }
}
package com.imooc.set;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;


public class DictionDemo {
    public static void main(String[] args) {
        Map<String,String> animal=new HashMap<String,String>();
        System.out.println("请输入三组单词对应的注释,并存放到HashMap中:");
        Scanner sc=new Scanner(System.in);
        //添加数据
        for(int i=0;i<3;i++) {
            System.out.println("请输入key的值:");
            String key=sc.next();
            System.out.println("请输入value的值:");
            String value=sc.next();
            animal.put(key,value);
        }
        //打印并输出value的值(直接使用迭代器)
        System.out.println("======================");
        System.out.println("使用迭代器输出所有value:");
        Iterator<String> it=animal.values().iterator();
        while(it.hasNext()) {
            System.out.print(it.next()+" ");
        }
        System.out.println();
        System.out.println("======================");
        //打印并输出key-value的值(直接entrySet)
        System.out.println("通过entrySet方法获得key-value:");
        Set<Entry<String, String>> entrySet=animal.entrySet();
        for(Entry<String, String> entry:entrySet) {
            System.out.print(entry.getKey()+"-");
            System.out.println(entry.getValue());
        }
        System.out.println();
        System.out.println("======================");
        //通过单词找到注释并输出
        //使用keySet方法
        System.out.println("请输入要查找的单词:");
        String strSearch=sc.next();
        //1.获取keySet
        Set<String> keySet=animal.keySet();
        //2.遍历keySet
        boolean flag=false;
        for(String key:keySet) {
            if(strSearch.equals(key)) {
                flag=true;
                break;
            }
        }
        if(flag) {
            System.out.println("找到了!"+"键值对为:"+strSearch+"-"+animal.get(strSearch));
        }else{
            System.out.println("抱歉,没有找到!");
        }
    }
}

案例2:商品信息管理
• 使用HashMap对商品信息进行管理
-其中key为商品编号,value为商品对象
• 对HashMap中的商品信息进行增、删、改、查操作
 
分析商品信息类
• 属性
-商品编号:id
-商品名称:name
-商品价格:price
• 方法
-构造方法
-获取和设置属性值的方法
-其他方法
package com.imooc.set;

public class Goods {
    private String id;//商品编号
    private String name;//商品名称
    private double price;//价格
    
    //构造方法
    public Goods(String id, String name, double price) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
    }
    //getter和setter

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "商品编号:" + id + ", 商品名称:" + name + ", 商品价格:" + price;
    }
    
}
package com.imooc.set;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

public class GoodsTest {

    public static void main(String[] args) {
        // 使用HashMap管理商品信息,并实现增删改查
        Scanner sc=new Scanner(System.in);
        //定义HashMap对象
        Map<String,Goods> goodsMap=new HashMap<String,Goods>();
        System.out.println("请输入三条商品信息:");
        int i=0;
        while(i<3) {
            System.out.println("请输入第"+(i+1)+"条商品信息:");
            System.out.println("请输入商品编号:");
            String goodsId=sc.next();
            System.out.println("请输入商品名称:");
            String goodsName=sc.next();
            System.out.println("请输入商品价格:");
            double goodsPrice=sc.nextDouble();
            Goods goods=new Goods(goodsId,goodsName,goodsPrice);
            goodsMap.put(goodsId,goods);
            i++;
        }
        //遍历map输出商品信息
        System.out.println("商品的全部信息为:");
        Iterator<Goods> it=goodsMap.values().iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }

}
package com.imooc.set;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

public class GoodsTest {

    public static void main(String[] args) {
        // 使用HashMap管理商品信息,并实现增删改查
        Scanner sc=new Scanner(System.in);
        //定义HashMap对象
        Map<String,Goods> goodsMap=new HashMap<String,Goods>();
        System.out.println("请输入三条商品信息:");
        int i=0;
        while(i<3) {
            System.out.println("请输入第"+(i+1)+"条商品信息:");
            System.out.println("请输入商品编号:");
            String goodsId=sc.next();
            //判断商品编号是否存在
            if(goodsMap.containsKey(goodsId)) {
                System.out.println("该商品编号已经存在,请重新输入!");
                continue;
            }
            System.out.println("请输入商品名称:");
            String goodsName=sc.next();
            System.out.println("请输入商品价格:");
            double goodsPrice=0;
            try {
                goodsPrice=sc.nextDouble();
            }catch(Exception e) {
                System.out.println("商品价格格式错误,请输入数值型数据!");
                sc.next();
                continue;
            }
            Goods goods=new Goods(goodsId,goodsName,goodsPrice);
            goodsMap.put(goodsId,goods);
            i++;
        }
        //遍历map输出商品信息
        System.out.println("商品的全部信息为:");
        Iterator<Goods> it=goodsMap.values().iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
        
        
    }

}
原文地址:https://www.cnblogs.com/loveapple/p/11142406.html