与JAVA集合相遇

2020-06-11 16:04:21来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

与JAVA集合相遇

1.集合框架的介绍

 

2.Collection集合常用功能

 

import java.util.ArrayList;
import java.util.Collection;

public class Main {
    public static void main(String[] args) {
        Collection coll=new ArrayList<>();
        System.out.println(coll);
        coll.add(56);
        coll.add(64);
        coll.add(36);
        coll.add(78);
        coll.add(194);
        System.out.println(coll);

        boolean b = coll.remove(78);
        System.out.println(b+"\n"+coll);
        boolean b1 = coll.remove(433);
        System.out.println(b1);

        boolean b2 = coll.contains(789);
        System.out.println(b2);

        boolean empty = coll.isEmpty();
        System.out.println(empty);

        coll.clear();//void

        System.out.println(coll);


    }
}

打印结果:

[]
[56, 64, 36, 78, 194]
true
[56, 64, 36, 194]
false
false
false
[]

3.Iterator迭代器

 

1.0 迭代器的代码实现

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {
        Collection<String> coll=new ArrayList<>();
        coll.add("金南俊");
        coll.add("金硕珍");
        coll.add("闵允其");
        coll.add("郑号锡");
        coll.add("朴智旻");
        coll.add("金泰亨");
        coll.add("田柾国");
        Iterator<String> it=coll.iterator();
        /*while循环

        while(it.hasNext())
        {
            String next = it.next();
            System.out.println(next);
        }
        */
        for(;it.hasNext();)
        {
            String next = it.next();
            System.out.println(next);

        }
    }
}

  

打印结果:

金南俊
金硕珍
闵允其
郑号锡
朴智旻
金泰亨
田柾国

 

 

4.增强for循环

 

 

 

import java.util.ArrayList;
import java.util.Collection;

public class Main {
    public static void main(String[] args) {
        demo01();//遍历数组
        demo02();//遍历集合
    }
    private static void demo01() {
        int arc[]={54,35,24,87,90};
        for (int i:arc) {
            System.out.println(i);
        }
    }
    private static void demo02() {
        Collection<String > coll=new ArrayList<>();
       coll.add("nanami");
       coll.add("巴卫");

        for (String s:coll
             ) {
            System.out.println(s);
        }
    }


}

打印结果:

54
35
24
87
90
nanami
巴卫

 

5.泛型

1.0 泛型的介绍

 

2.0 泛型的好处

3.0 定义和使用含有泛型的类

 

public class  Person<E> {
    private E name;

    public Person() {
    }

    public E getName() {
        return name;
    }

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

    public Person(E name) {
        this.name = name;
    }
}

  

public class Main{
    public static void main(String[] args) {
        /*
          Person people=new Person();
          people.setName("Mary");
          String name = people.getName();
           System.out.println(name.length());
       */

        Person <Integer> people=new Person<>();
       people.setName(23);
        System.out.println(people.getName());


    }
}

  

 

4.0定义和使用含有泛型的方法

public class Demo {
    public <E> void demo01(E elem){
        System.out.println(elem);
    }

}

  

public class Main{
    public static void main(String[] args) {
    Demo de=new Demo();

    de.demo01("ashgfd");
    }
}

5.0定义和使用含有泛型的接口

 

 

 

public interface Interfaced<E>{
    public abstract void method(E elem);
}

  

public interface Interfaced1<E>{
    public abstract void method1(E elem1);
}

  

public class Demo implements Interfaced<String>{

    @Override
    public void method(String elem) {
        System.out.println(elem);
    }
}

  

public class Demo1<I> implements Interfaced1<I> {

    @Override
    public void method1(I elem1) {
        System.out.println(elem1);
    }
}

  

public class Main{
    public static void main(String[] args) {
        Demo demo=new Demo();
        demo.method("fhdsg");
        Demo1<String > demo1=new Demo1<>();
        demo1.method1("fsvrg");
    }
}

6.0 泛型的通配符

使用案例:

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> list1=new ArrayList<>();
        list1.add(564);
        list1.add(85);
        list1.add(22);
        list1.add(54);
        ArrayList<String> list2=new ArrayList<>();
        list2.add("fhr");
        list2.add("mzq");
        print(list1);
        print(list2);
    }

    private static void print(ArrayList<?> list) {
        Iterator<?> it=list.iterator();
        while(it.hasNext())
        {
            Object next = it.next();
            System.out.println(next);

        }
    }
}

 

打印结果:

564
85
22
54
fhr
mzq

 

6.集合小练习

欢乐斗地主

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class Cardsgame {
    public static void main(String[] args) {
        //准备牌
        ArrayList<String> cards=new ArrayList<>();
        String[] colors={"黑桃","方块","红桃","梅花"};
        String[] numbers={"2","A","K","Q","J","10","9","8","7","6","5"
        ,"4","3"};
        for (String color : colors) {
            for (String number : numbers) {
                cards.add(color+number);
            }
        }
        cards.add("大王");
        cards.add("小王");
        //洗牌
        //使用集合工具类 Collections中的方法 static void shuffle(List<?> List)
        //使用默认随机源对指定列表进行置换
        Collections.shuffle(cards);

        //发牌

        ArrayList<String> player1=new ArrayList<>();
        ArrayList<String> player2=new ArrayList<>();
        ArrayList<String> player3=new ArrayList<>();
        ArrayList<String> lowcards=new ArrayList<>();
        for(int i=0;i<cards.size();i++)
        {
            String s = cards.get(i);
            if(i>=51)
            {
                lowcards.add(s);
            }
            else
            {
                if(i%3==0) player1.add(s);
                else if(i%3==1) player2.add(s);
                else player3.add(s);
            }
        }
        System.out.println("玩家1"+player1);
        System.out.println("玩家2"+player2);
        System.out.println("玩家3"+player3);
        System.out.println("底牌"+lowcards);
    }
}

 

打印结果:

玩家1[红桃J, 梅花10, 黑桃6, 梅花4, 梅花5, 方块A, 梅花2, 红桃Q, 黑桃4, 方块10, 方块6, 红桃7, 红桃4, 红桃K, 红桃9, 黑桃A, 梅花A]
玩家2[黑桃10, 方块7, 红桃6, 梅花K, 黑桃7, 梅花8, 方块4, 梅花9, 红桃8, 大王, 黑桃2, 梅花J, 红桃5, 黑桃3, 黑桃Q, 红桃2, 梅花6]
玩家3[方块8, 方块2, 小王, 黑桃8, 黑桃9, 方块K, 梅花Q, 方块9, 方块3, 黑桃5, 红桃10, 黑桃K, 红桃A, 方块Q, 梅花3, 梅花7, 方块5]
底牌[红桃3, 黑桃J, 方块J]

 

7.List接口

 

 

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

public class Main{
    public static void main(String[] args) {
        //获取List集合 多态
        List<String> list=new ArrayList<>();

        //add()
        list.add("bts");
        list.add("dsfh");
        list.add("shdgf");
        list.add("sunshine");
        list.add(1,"Army");
        System.out.println(list);

        //remove
        String remove = list.remove(2);
        System.out.println(remove);
        System.out.println(list);

        //set
        list.set(2,"love");
        System.out.println(list);

        //get
        //遍历
        /*迭代器*/

        Iterator<String> iterator = list.iterator();
        while(iterator.hasNext()  )
        {
            String next = iterator.next();
            System.out.println(next);
        }

        /*for*/
        for(int i=0;i<list.size();i++)
        {
            String s = list.get(i);
            System.out.println(s);

        }
        
        /*foreach*/

        for (String s : list) {
            System.out.println(s);
        }
    }
}

 

 

打印结果

[bts, Army, dsfh, shdgf, sunshine]
dsfh
[bts, Army, shdgf, sunshine]
[bts, Army, love, sunshine]
bts
Army
love
sunshine
bts
Army
love
sunshine
bts
Army
love
sunshine

 

 

8.LinkedList集合

 

import java.util.LinkedList;

public class Main{
    public static void main(String[] args) {
        show1();//add
        show2();//get
        show3();//remove
    }

    private static void show3() {
        LinkedList<String> linked = new LinkedList<>();
        linked.add("you");
        linked.add("are");
        linked.add("mine");
        String s = linked.removeFirst();
        System.out.println("弹出的第一个元素为"+s);
        linked.removeLast();
        linked.pop();//removefirst()
        System.out.println(linked);
        boolean empty = linked.isEmpty();
        System.out.println(empty);
    }

    private static void show2() {
        LinkedList<String > linked = new LinkedList<>();
        linked.add("a");
        linked.add("b");
        linked.add("c");
        System.out.println("集合的首元素为:"+linked.getFirst());
        System.out.println("集合的尾元素为:"+linked.getLast());
    }

    private static void show1() {
        LinkedList<String> linked = new LinkedList<>();
        linked.add("love");
        //linked.addFirst("I");//push
        linked.push("I");
        linked.addLast("you");//add
        System.out.println(linked);
    }
}

  

打印结果:

[I, love, you]
集合的首元素为:a
集合的尾元素为:c
弹出的第一个元素为you
[]
true

9.Set接口

 

 

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

public class Main{
    public static void main(String[] args) {
        Set<Integer> set=new HashSet<>();
        set.add(1);
        set.add(4);
        set.add(3);
        set.add(1);
        System.out.println(set);
        //遍历集合
        /*迭代器*/
        Iterator<Integer> iterator = set.iterator();
        while(iterator.hasNext())
        {
            Integer next = iterator.next();
            System.out.println(next);
        }
        System.out.println("=============");

        /*foreach*/
        for (Integer integer : set) {
            System.out.println(integer);
        }
    }
}

 

打印结果:

[1, 3, 4]
1
3
4
=============
1
3
4

 

HashSet集合存储数据的结构

Hashset集合存储自定义元素

import java.util.Objects;

public class Person{
    private String name;
    private int age;

    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;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

  

import java.util.HashSet;

public class Main{
    public static void main(String[] args) {
        Person p1=new Person("V",25);
        Person p2=new Person("V",25);
        Person p3=new Person("V",18);
        HashSet<Person> people = new HashSet<>();
        people.add(p1);
        people.add(p2);
        people.add(p3);
        System.out.println(people);//重写了toString方法
        /*
        //[Person{name='V', age=18}, Person{name='V', age=25}, Person{name='V', age=25}]
        boolean equals = p1.equals(p2);
        System.out.println(equals);//false
        System.out.println("p1:"+p1.hashCode()+" p2:"+p2.hashCode());
        //所以 equals比较为false 且哈希值不一样 所以元素不一样
        */
        //重写Hashcode equals
        boolean equals = p1.equals(p2);
        System.out.println(equals);//true
        System.out.println("p1:"+p1.hashCode()+" p2:"+p2.hashCode());//3652
        //[Person{name='V', age=25}, Person{name='V', age=18}]

    }
}

 

LinkedHashSet集合

 

import java.util.HashSet;
import java.util.LinkedHashSet;

public class Main{
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("add");
        set.add("tre");
        set.add("bde");
        set.add("add");
        System.out.println(set);//[add, bde, tre] 无序 不重复

        LinkedHashSet<String> linked = new LinkedHashSet<>();
        linked.add("add");
        linked.add("tre");
        linked.add("bde");
        linked.add("add");
        System.out.println(linked);//[add, tre, bde] 有序 不重复

    }
}

 

10.哈希值

 

import java.util.Objects;

public class Main{
    public static void main(String[] args) {
        Person p1 = new Person();
        Person p2 = new Person();
        int h1, h2;
        h1 = p1.hashCode();
        h2 = p2.hashCode();
        System.out.println(h1);//1355531311
        System.out.println(p1);//实际 Person@50cbc42f
        System.out.println(h2);//1967205423
        System.out.println(p2);//Person@75412c2f

        //String类的哈希值重写了toString
        String s1=new String("abc");
        String s2=new String("abc");
        System.out.println(s1.hashCode());//96354
        System.out.println(s2.hashCode());//96354

        System.out.println("重地".hashCode());//1179395
        System.out.println("通话".hashCode());//1179395

    }
}

 

11.Collections集合工具类

1.0 Collections的方法

import java.util.ArrayList;
import java.util.Collections;

public class Main{
    public static void main(String[] args) {
        ArrayList<Integer> array = new ArrayList<>();
        Collections.addAll(array,1,2,3,4,5,6,7,8,9);
        System.out.println(array);

        Collections.shuffle(array);
        System.out.println(array);
    }
}

 

打印结果:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 9, 3, 7, 8, 2, 4, 6, 1]

 

2.0 Collections.sort()

1)public static<T> void sort(list<T> list)

 

 

import java.util.Objects;

public class Person implements Comparable<Person>{
    private String name;
    private int age;

    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;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Person o) {
        //按年龄排序
        return this.getAge()-o.getAge();
       }
}

  

import java.util.ArrayList;
import java.util.Collections;

public class Main{
    public static void main(String[] args) {
        ArrayList<Integer> array = new ArrayList<>();
        Collections.addAll(array,45,23,9,56,10);
        System.out.println(array);
        Collections.sort(array);
        System.out.println(array);

        //自定义的类
        ArrayList<Person> list = new ArrayList<>();
        Person p1=new Person("V",25);
        Person p2=new Person("JK",23);
        Person p3=new Person("Jimin",25);
        Collections.addAll(list,p1,p2,p3);
       //重写compareTo
        Collections.sort(list);
        System.out.println(list);
    }
}

 

 

打印结果:

[45, 23, 9, 56, 10]
[9, 10, 23, 45, 56]
[Person{name='JK', age=23}, Person{name='V', age=25}, Person{name='Jimin', age=25}]

2)public static <T> void sort(List<T> list,Comparator<? super T>)

 

 

public class Students {
    private String name;
    private int age;

    @Override
    public String toString() {
        return "Students{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    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 Students() {
    }

    public Students(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

  

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main{
    public static void main(String[] args) {
        ArrayList<Students> students = new ArrayList<>();
        Students s1=new Students("Lisa",23);
        Students s2=new Students("Jisoo",25);
        Students s3=new Students("Rose",23);
        Students s4=new Students("Jennie",24);
        Collections.addAll(students,s1,s2,s3,s4);
        Collections.sort(students, new Comparator<Students>() {
            @Override//匿名内部类
            public int compare(Students o1, Students o2) {
                return o1.getAge()-o2.getAge()  ;//按年龄升序
            }
        });
        System.out.println(students);

        //多个条件排序
        //年龄一样 按名字首字母从大到小排列
        Collections.sort(students, new Comparator<Students>() {
            @Override
            public int compare(Students o1, Students o2) {
                int result=o1.getAge()-o2.getAge();
                if(result==0)
                {
                    result=o2.getName().charAt(0)-o1.getName().charAt(0);
                }
                return result;
            }
        });
           System.out.println(students);

    }
}

 

打印结果:

[Students{name='Lisa', age=23}, Students{name='Rose', age=23}, Students{name='Jennie', age=24}, Students{name='Jisoo', age=25}]
[Students{name='Rose', age=23}, Students{name='Lisa', age=23}, Students{name='Jennie', age=24}, Students{name='Jisoo', age=25}]

 

12.Map集合

1.0 Map集合的概述以及常用子类

 

2.0 Map接口中的常用方法

 

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

public class Main{
    public static void main(String[] args) {
        Map<String,Integer> map=new HashMap<>();
        //put方法
        Integer jimin = map.put("Jimin", 25);
        System.out.println(jimin);//null
        Integer jimin1 = map.put("Jimin", 26);
        System.out.println(jimin1);//25
        map.put("V",25);
        map.put("JK",23);
        System.out.println(map);
        //{JK=18, V=25, Jimin=26}

        //remove()
        Integer jimin2 = map.remove("Jimin");
        System.out.println(jimin2);//26
        System.out.println(map);
        //{JK=18, V=25}

        //get()
        Integer jk = map.get("JK");
        System.out.println("JK的年龄为:"+jk);
        //JK的年龄为:23

        //containsKey()
        boolean b = map.containsKey("Jhope");
        System.out.println(b);//false
    }
}

 

3.0 Map集合遍历键找值

 

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

public class Main{
    public static void main(String[] args) {
        Map<String,Integer> map=new HashMap<>();
        map.put("RM",27);
        map.put("Jin",28);
        map.put("JK",23);

        Set<String> set = map.keySet();
        Iterator<String> iterator = set.iterator();

        //迭代器
        while(iterator.hasNext())
        {
            String key = iterator.next();
            Integer value = map.get(key);
            System.out.println(key+" "+value);
        }

        System.out.println("==============");
        //foreach

        for (String s : set) {
            System.out.println(s+" "+map.get(s));
        }
    }
}

  

打印结果:

JK 23
RM 27
Jin 28
==============
JK 23
RM 27
Jin 28

4.0 Map集合遍历键值对方式

 

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

public class Main{
    public static void main(String[] args) {
        Map<String,String> map=new HashMap<>();
        map.put("金泰亨","V");
        map.put("朴智旻","Jimin");
        map.put("田柾国","JK");

        Set<Map.Entry<String, String>> entries = map.entrySet();
        Iterator<Map.Entry<String, String>> it = entries.iterator();
        while(it.hasNext()){
            Map.Entry<String, String> next = it.next();
            String key = next.getKey();
            String value = next.getValue();
            System.out.println(key+" "+value);
        }

        System.out.println("=====================");
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+" "+value);
        }


    }
}

 

打印结果:

朴智旻 Jimin
金泰亨 V
田柾国 JK
=====================
朴智旻 Jimin
金泰亨 V
田柾国 JK

5.HashMap存储自定义类型

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

public class Main{
    public static void main(String[] args) {
        //<String,Person> key值不重复 String重写Hashcode 和equals
        HashMap<String,Person> map=new HashMap<>();
        map.put("bts",new Person("金泰亨",25));
        map.put("bts",new Person("田柾国",23));
        map.put("blackpink",new Person("Lisa",23));
        Set<String> set= map.keySet();
        for (String s : set) {
            Person person = map.get(s);
            System.out.println(s+" "+person);
        }

        System.out.println("==================");

        //<Person,String> key值不重复 Person重写Hashcode 和equals

        HashMap<Person, String> map1 = new HashMap<>();
        map1.put(new Person("Jimin",25),"BTS");
        map1.put(new Person("Jimin",25),"bts");
        map1.put(new Person("Jin",28),"BTS");
        Set<Map.Entry<Person, String>> set1 = map1.entrySet();
        for (Map.Entry<Person, String> entry : set1) {
            Person key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+" "+value);


        }

    }
}

  

打印结果:

bts Person{name='田柾国', age=23}
blackpink Person{name='Lisa', age=23}
==================
Person{name='Jimin', age=25} bts
Person{name='Jin', age=28} BTS

 

6.LinkedHashmap集合

继承了HashMap集合 哈希表+链表(记录存储的顺序)

import java.util.HashMap;
import java.util.LinkedHashMap;

public class Main{
    public static void main(String[] args) {
        HashMap<String, Integer> hashmap = new HashMap<>();
        hashmap.put("V",25);
        hashmap.put("RM",26);
        hashmap.put("Suga",27);
        hashmap.put("JK",23);
        System.out.println(hashmap);
        //{JK=23, V=25, RM=26, Suga=27}
        System.out.println("==============================");
        LinkedHashMap<String,Integer> map=new LinkedHashMap<>();
        map.put("V",25);
        map.put("RM",26);
        map.put("Suga",27);
        map.put("JK",23);
        System.out.println(map);
        //{V=25, RM=26, Suga=27, JK=23}
    }
}

  

7.Hashtable集合

 

8.Map集合的小应用

计算字符串中每个字符的个数

import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

public class Main{
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String str=input.next();
        HashMap<Character, Integer> map = new HashMap<>();
        for (char c : str.toCharArray()) {
            if(map.containsKey(c)){
                //存在
                Integer value = map.get(c);
                value++;
                map.put(c,value);
            }
            else
            {
                map.put(c,1);
            }
        }
        Set<Character> set = map.keySet();
        for (Character key : set) {
            System.out.println("字符:"+key+" 个数为:"+map.get(key));
        }
    }
}

 

打印结果:

请输入一个字符串:

sdhgfgdsfiwe
字符:s 个数为:2
字符:d 个数为:2
字符:e 个数为:1
字符:f 个数为:2
字符:g 个数为:2
字符:w 个数为:1
字符:h 个数为:1
字符:i 个数为:1

 

 

 

13.JDK9对集合添加的优化

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

public class Main{
    public static void main(String[] args) {
        List<String> list = List.of("a", "b", "c", "d");
        System.out.println(list);
       // list.add("e");//UnsupportedOperationException

        //Set<String> set = Set.of("e", "f", "g", "h","e");//重复元素
        //IllegalArgumentException
        //System.out.println(set);


        Map<String, Integer> map = Map.of("V", 25, "JK", 23, "Jimin", 25);

        System.out.println(map);
        //key不能重复   IllegalArgumentException: duplicate key: V
        //Map<String, Integer> map1 = Map.of("V", 25, "JK", 23 , "Jimin", 25,"V", 25);

    }
}

  

 

打印结果:

[a, b, c, d]
{V=25, JK=23, Jimin=25}


原文链接:https://www.cnblogs.com/mzq-/p/13049027.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:如何干掉 if else 策略+工厂

下一篇:SpringBoot 2.3 整合最新版 ShardingJdbc + Druid + MyBatis 实