自学内容网 自学内容网

木舟0基础学习Java的第十五天(集合嵌套,Set集合,比较器,Map集合)

集合嵌套

 public static void main(String[] args) {
        //集合嵌套
        //定义一个集合 放集合one,two 以ArrayList<Person> 为泛型
        ArrayList<ArrayList<Person>> list=new ArrayList();

        ArrayList<Person> one=new ArrayList();
        ArrayList<Person> two=new ArrayList();
        one.add(new Person("张三",23));
        one.add(new Person("李四",24));
        one.add(new Person("王五",25));

        two.add(new Person("李雷",18));
        two.add(new Person("韩梅梅",19));
        two.add(new Person("王铁钢",20));
        //将两个集合放入list集合中
        list.add(one);
        list.add(two);
        //循环遍历
        for (ArrayList<Person> lists : list) {
            for (Person p :lists ) {
                System.out.println(p.getName()+p.getAge());
            }
        }
    }

Set集合

接口 无顺序 不可重复

HashSet:底层为哈希算法

              :LinkedSet:Set体系下唯一可以保证存取顺序的

TreeSet:底层为二叉树  目的:对set集合中的数据进行排序

方法:与List中的方法相同

HashSet:

HashSet去重是底层通过哈希码和equals完成的

LinkedHashSet:特点可以保证怎么存就怎么取

TreeSet:

排序去重 底层会把存入TreeSet集合的数据进行自然顺序排序

里面有compare:return (x<y)? -1:((x==y)?0:1)

使用二叉树存储对象 排序去重 需要实现(implements)Comparable<对象>

重写compareTo方法 如果返回值为0 那么只存第一个对象

返回负数倒着存 返回正数就按顺序存

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

    public Person() {
    }

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

    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 float getScore() {
        return score;
    }

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

    @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 && Float.compare(score, person.score) == 0 && Objects.equals(name, person.name);
    }

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

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}
public class ComPerson implements Comparator<Person> {
    @Override
    public int compare(Person o1, Person o2) {
        int n1=(int)(o1.getScore()-o2.getScore());//分数
        int n2=o1.getAge()-o2.getAge();//年龄
        int n3=o1.getName().compareTo(o2.getName());//名字
        int result=0;
        //不是同一个人 按成绩降序
        if((n2+n3)!=0){
            result=-n1;
            //如果成绩相同 不去重 按年龄排序
            if(result==0){//成绩相同
                //比较年龄
                result=n2;//年龄相同
                result=result==0?1:result;//一前一后
            }
        }
        return result;
    }
}
   TreeSet<Person> ts=new TreeSet<>(new ComPerson());
        ts.add(new Person("张三",23,90f));
        ts.add(new Person("李四",24,95f));
        ts.add(new Person("李四",24,95f));
        ts.add(new Person("王五",22,91f));
        ts.add(new Person("王五",22,91f));
        System.out.println(ts);

比较器(降低程序之间的耦合度)

1.创建比较器 实现 Comparator<类>
2.重写compareTo方法 
3.修改想要比较的返回值
例:
public class CheckAge implements Comparator<Student> {
    //通过年龄排序
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getAge()-o2.getAge();
    }
}
public class CheckName implements Comparator<Student> {
    //通过名字排序
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getName().compareTo(o2.getName());
    }
}
 public static void main(String[] args) {
        //创建一个带比较器的集合
        TreeSet<Student> ts=new TreeSet(new CheckName());
        //TreeSet<Student> ts=new TreeSet(new CheckAge());
        ts.add(new Student("张三",23));
        ts.add(new Student("张三",23));
        ts.add(new Student("李四",24));
        ts.add(new Student("李四",24));
        ts.add(new Student("王五",25));
        ts.add(new Student("王五",25));
        System.out.println(ts);
    }
不去重 但排序
public class ComString implements Comparator<Character> {
    //不去重 但排序
    @Override
    public int compare(Character o1, Character o2) {
        int num1=o1.compareTo(o2);
        int num2=num1==0?1:num1;
        return num2;
    }
}

案例:

 public static void main(String[] args) {
        //让其有序(按字典顺序) 不去重
        String s="liaoninglianningliaoning";
        sort(s);
    }
    public static void sort(String s){
        TreeSet<Character> ts=new TreeSet(new ComString());
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            ts.add(c);
        }
        System.out.println(ts);
    }

字符串转换回基本数据类型(parse)

 public static void main(String[] args) {
        int a=Integer.parseInt("123");//123
        float b=Float.parseFloat("123f");//123.0
        short c=Short.parseShort("123");//123
        byte d=Byte.parseByte("1");//1
        double e=Double.parseDouble("123");//123.0
      //  double f=Double.parseDouble("a");//报错 转换异常
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        System.out.println(e);
       // System.out.println(f);

    }

Map集合

HashMap:重点 springMVC携带服务器数据到前端

Map<key,value>键,值

Map集合添加元素特点:map.put();

如果键 是第一次存储 就直接存储元素 返回null

如果键 不是第一存储 就用值将以前的值替换掉 返回以前的值

Map<Integer,String> m=new HashMap();

根据键获取值:

m.get(键);

返回所有键的集合:

方法1(有迭代器)

m.keySet();//.var

Set<Integer> s = m.keySet();

//遍历map 通过遍历装有键的Set集合 获得对应的所有值

Iterator<Integer> i=s.iterator();

while(i.hasNext()){

Integer key = i.next();

String value = m.get(key);

System.out.println("key"+key+",value"+value);

}

方法2(增强for循环)

for (Integer key : m.keySet())

{ System.out.println("key"+key+",value"+m.get(key)); }

方法3(映射Map.Entry)

Map<Integer,String> m=new HashMap();

m.put(1,"沈阳"); m.put(2,"大连"); m.put(3,"营口");

Set<Map.Entry<Integer,String>> me=m.entrySet();//视图

for (Map.Entry<Integer, String> mm : me) {

mm.getKey();

mm.getValue();

System.out.println( mm.getKey()+ mm.getValue());

}

获取集合中所有值的集合

Collection<String> values = m.values().var;

获取键值对的个数

m.size();

LinkedHashMap(底层是链表)

特点:怎么存就怎么取

 public static void main(String[] args) {
        LinkedHashMap<Integer,String> lhm=new LinkedHashMap<>();
        lhm.put(1,"营口");
        lhm.put(1,"营口");
        lhm.put(3,"大连");
        lhm.put(3,"大连");
        lhm.put(2,"沈阳");
        lhm.put(2,"沈阳");
        Set<Map.Entry<Integer, String>> ent = lhm.entrySet();
        Iterator<Map.Entry<Integer, String>> i=ent.iterator();
        while(i.hasNext()){
            Map.Entry<Integer, String>me= i.next();
            Integer key = me.getKey();
            String value = me.getValue();
            System.out.println(key+value);
        }
    }

TreeMap

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

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.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;
    }

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

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

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
public class ComStu implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getAge()-o2.getAge();
    }
}
   public static void main(String[] args) {
        TreeMap<Student,String> tm=new TreeMap(new ComStu());
        tm.put(new Student("张三",23),"沈阳");
        tm.put(new Student("张三",23),"沈阳");
        tm.put(new Student("李四",22),"大连");
        tm.put(new Student("李四",22),"大连");
        tm.put(new Student("王五",25),"营口");
        tm.put(new Student("王五",25),"营口");
        System.out.println(tm);
    }


原文地址:https://blog.csdn.net/tzh525/article/details/140312611

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!