目录
可变参数
Collections
小案例:斗地主游戏
Map集合
Map的常用方法
map集合的遍历
键找值
键值对
Lambda 表达式
HashMap底层原理
集合的嵌套
Stream流
获取集合或数组的Stream流
Stream流的方法
可变参数
就是一种特殊的形参,定义在方法和构造器的形参列表中,格式是: 数据类型...参数名称
外部可以接受多个该类型的参数,也可以接收这个参数的数组
而他的内部是一个数组
一个形参列表只能由一个可变参数
可变参数要放到形参列表的后面
public class zheng {public static void main(String[] args) {test(); // 不传数据test(10); // 传一个数据给它test(10,20,30); // 传输多个数据给他test(new int[]{10,20,30,40,50}); // 传输一个数组给可变参数}public static void test(int...number) {// 可变参数在方法内部,本质上是一个数组System.out.println(number.length);System.out.println(Arrays.toString(number));System.out.println("---------------------");}
}
Collections
工具类: 类名.方法 有static修饰的
public class zheng {public static void main(String[] args) {// 1.public static <T> boolean addAll(Collection<? super T> c,T...elements):// 为集合批量添加数据List<String> names = new ArrayList<>();Collections.addAll(names, "张三","王五","李四","张麻子");System.out.println(names);// 2.public static void shuffle(List<?> list) 打乱List集合中的元素顺序Collections.shuffle(names);System.out.println(names);// 3.public static <T> void sort(List<T> list) 对List集合中的元素进行升序排序List<Integer> list = new ArrayList<>();list.add(3);list.add(5);list.add(2);Collections.sort(list);System.out.println(list);}
}
下面时设置表示方法
// 比较的对象不能排序的时候,那就方法重写List<Student>Student = new ArrayList<>();Student.add(new Student("李小谦",18,100));Student.add(new Student("李玉刚",58,90));Student.add(new Student("李德华",48,60));Collections.sort(Student);System.out.println(Student);// 实现接口的匿名内部类Collections.sort(Student, new Comparator<bag5.Student>() {@Overridepublic int compare(bag5.Student o1, bag5.Student o2) {return Double.compare(o1.getScore(),o2.getScore());}});
上面的方法1在Student中的实现类是
上面就是相当于用sort方法的时候,给出了Student具体按照什么指标来排序
小案例:斗地主游戏
main类
package bag5;import org.w3c.dom.ls.LSOutput;import java.sql.SQLOutput;
import java.util.*;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class zheng {public static void main(String[] args) {// 1.牌类// 2.房间// 3.创建一个房间Room room = new Room();// 3.启动游戏room.start();}}
创建一个Card类,用来创建Card对象
package bag5;public class Card {private String color;private String number;private int size;public Card() {}public Card(String color, String number, int size) {this.color = color;this.number = number;this.size = size;}@Overridepublic String toString() {return color+number;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public String getNumber() {return number;}public void setNumber(String number) {this.number = number;}public int getSize() {return size;}public void setSize(int size) {this.size = size;}
}
创建一个房间类
package bag5;import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;public class Room {// 必须有一副牌private List<Card> allCards = new ArrayList<>();List<Card> lingHuChong = new ArrayList<>();List<Card> lixiaoqian = new ArrayList<>();List<Card> zhangsanfeng = new ArrayList<>();public Room(){// 1. 做出54张牌,存入集合allCards// a. 点数: 个数确定,类型确定String[] numbers = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};String[] colors = {"♥","🖤","♣","♦"};int size = 0;for(String number: numbers){size++;for(String color:colors){Card c = new Card(number,color,size);allCards.add(c);}}// 单独存入小大王Card c1 = new Card("","小王",++size);Card c2 = new Card("","大王",++size);Collections.addAll(allCards,c1,c2);System.out.println(allCards);}public void start(){// 1. 洗牌: allCardsCollections.shuffle(allCards);System.out.println("洗牌后: "+ allCards);// 2. 发牌: 首先定义三个玩家(ArrayList)for (int i = 0; i < allCards.size() - 3; i++) {Card c = allCards.get(i);if (i % 3 == 0){lingHuChong.add(c);}else if(i%3 == 1){lixiaoqian.add(c);}else {zhangsanfeng.add(c);}}// 底牌List<Card> lastTreeCards = allCards.subList(allCards.size() - 3,allCards.size());//对排进行排序sortCards(lixiaoqian);sortCards(lingHuChong);sortCards(zhangsanfeng);lixiaoqian.addAll(lastTreeCards);System.out.println(lixiaoqian);System.out.println(lingHuChong);System.out.println(zhangsanfeng);}private void sortCards (List<Card> cards ){Collections.sort(cards, new Comparator<Card>() {@Overridepublic int compare(Card o1, Card o2) {return o1.getSize() - o2.getSize();}});}}
Map集合
称为双列集合,格式: {key1 = value1,key2=value2}一次需要存一对数据作为一个元素
Map集合的每个元素,"key=value"称为一个键值对/键值对对象/一个Entry对象
Map集合所有键是不允许重复的,但值可以重复,键和值一一对应,每一个键都有自己对应的值
public class map11 {public static void main(String[] args) {Map<String,Integer> map = new HashMap<>();map.put("手表",100);map.put("手表",10);// 后面重复的数据会覆盖前面的数据map.put("手帕",1200);map.put("电脑",300);map.put("手机",500);System.out.println(map);} }
Map的常用方法
public class map11 {public static void main(String[] args) {Map<String,Integer> map = new HashMap<>();map.put("手表",100);map.put("手表",10);// 后面重复的数据会覆盖前面的数据map.put("手帕",1200);map.put("电脑",300);map.put("手机",500);System.out.println(map);// 获取集合的大小System.out.println(map.size());// 清空map.clear();System.out.println();// 判断是否为空System.out.println(map.isEmpty());// 获取键对应的值int v1 = map.get("手表");System.out.println(v1);System.out.println(map.get("手机"));System.out.println(mao.get("李小谦"));// public V remove (Object key) 根据键删除整个元素(删除键会返回键的值)System.out.println(map.remove("手表"));System.out.println(map);// public boolean containsKey(Object key) 判断是否包含某个值System.out.println(map.containsKey("手表"));System.out.println(map.containsKey("手机"));System.out.println(map.containsKey("Java"));System.out.println(map.containsKey("java"));// public boolean containValue(Object value): 判断是否包含某个键System.out.println(map.containsValue(100));// public Set<K> keySet 获取Map集合中全部键Set<String> set = map.keySet();System.out.println(set);// public Collection<V> values() 获取Map集合中的全部值Collection<Integer> list = map.values();System.out.println(list);// 把其他map数据倒入自己集合中Map<String,Integer>map1 = new HashMap<>();map1.put("java",10);map1.put("python",100);Map<String,Integer>map2 = new HashMap<>();map2.put("java",20);map2.put("C++",100);}
}
map集合的遍历
键找值
大体思路就是,将键取出来封装成一个Set对象,然后遍历Set中的键去get到Map中的值
public class map11 {public static void main(String[] args) {Map<String,Double> map = new HashMap<>();map.put("蜘蛛精",162.5);map.put("蜘蛛精",169.8);map.put("紫霞",165.8);map.put("至尊宝",169.5);map.put("牛魔王",183.6);System.out.println(map);// 1. 获取Map集合的全部键Set<String> keys = map.keySet();System.out.println(keys);// 2. 遍历全部的键,根据键获取对应的值for (String key : keys) {Double value = map.get(key);System.out.println(value.doubleValue());System.out.println(key + "====>" + value);}}
}
键值对
将"键值对"看成一个整体进行遍历
public class map11 {public static void main(String[] args) {Map<String,Double> map = new HashMap<>();map.put("蜘蛛精",162.5);map.put("蜘蛛精",169.8);map.put("紫霞",165.8);map.put("至尊宝",169.5);map.put("牛魔王",183.6);System.out.println(map);Set<Map.Entry<String,Double>> set= map.entrySet();for (Map.Entry<String, Double> stringDoubleEntry : set) {String key = stringDoubleEntry.getKey();double value = stringDoubleEntry.getValue();System.out.println(key+ "----->"+ value);}}
}
Lambda 表达式
public class map11 {public static void main(String[] args) {Map<String,Double> map = new HashMap<>();map.put("蜘蛛精",162.5);map.put("蜘蛛精",169.8);map.put("紫霞",165.8);map.put("至尊宝",169.5);map.put("牛魔王",183.6);System.out.println(map);map.forEach((k,v)->{System.out.println(k+"---->"+v);});map.forEach(new BiConsumer<String, Double>() {@Overridepublic void accept(String k, Double v) {System.out.println(k+"---->"+v);}});}
}
HashMap底层原理
集合的嵌套
集合的元素又是一个集合
public class map11 {public static void main(String[] args) {Map<String,List<String>> map = new HashMap<>();List<String> cities1 = new ArrayList<>();Collections.addAll(cities1,"南京市","扬州市","苏州市","无锡市","常州市");map.put("江苏省",cities1);List<String> cities2 = new ArrayList<>();Collections.addAll(cities2,"武汉市","孝感市","宜昌","鄂州市","三峡市");map.put("湖北省",cities2);System.out.println(map);List<String> cities = map.get("湖北省");for (String city : cities) {System.out.println(city);}map.forEach((p,c)->{System.out.println(p+"*******"+c);});}
}
Stream流
获取集合或数组的Stream流
public class map11 {public static void main(String[] args) {// 1. 获取ArrayList的stream流List<String> names = new ArrayList<>();Collections.addAll(names,"李小谦","李玉刚","张三","罗翔");Stream<String> stream = names.stream();// 2.获取Set集合中的Stream流Set<Integer> set = new HashSet<>();Collections.addAll(set , 4,5,6,7,8);Stream<Integer> stream1 = set.stream();stream1.filter(s->(s%2 == 0)).forEach(s-> System.out.println(s));// 3. 获取Map集合的Stream流Map<String,Double> map = new HashMap<>();map.put("古力娜扎",172.6);map.put("迪丽热巴",175.2);map.put("欧阳娜娜",173.2);// map.stream();// 拿到键的Stream流Set<String> keys= map.keySet();Stream<String> ks = keys.stream();// 拿到值的Stream流Collection<Double> values = map.values();Stream<Double> vs = values.stream();// 键值对的Stream流Set<Map.Entry<String,Double>> entries = map.entrySet();Stream<Map.Entry<String,Double>> kvs = entries.stream();kvs.filter(e->e.getKey().contains("巴")).forEach(e-> System.out.println(e.getKey() + "-----" + e.getValue()));// 数组中的Stream流String[] names2 = {"张翠山","东方不败","堂大山","独孤九剑"};Stream<String> s1 = Arrays.stream(names2);Stream<String> s2 = Stream.of(names2);}
}
Stream流的方法
先设置一个学生类
package bag6;import java.util.Objects;public class Student implements Comparable<Student>{// 实现这个结构就是调用排序的时候,排序的方法知道了比较规则// this o@Overridepublic int compareTo(Student o) {// 如果认为左边对象大于右边对象返回正整数//如果认为左边对象小于右边对象返回负数// 如果认为左边等于右边返回0// this表示调用的,o表示被比较的return this.age - o.age;}private String name;private int age;private double Height;@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", Height=" + Height +'}';}// 去重的时候按照值去重,不看hashCode@Overridepublic 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 && Double.compare(student.Height, Height) == 0 && Objects.equals(name, student.name);}@Overridepublic int hashCode() {return Objects.hash(name, age, Height);}public Student() {}public Student(String name, int age, double score) {this.name = name;this.age = age;this.Height = 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 double getScore() {return Height;}public void setScore(double score) {this.Height = score;}
}
常用方法
public class map11 {public static void main(String[] args) {List<Double> scores = new ArrayList<>();Collections.addAll(scores,88.5,100.0,60.0,99.0,9.5,99.6);// 需求1: 找出成绩大于60分的数据,并升序后,再输出List<Double> S = scores.stream().filter(s->s>60).collect(Collectors.toList());Student s1 = new Student("蜘蛛精",26,172.5);Student s2 = new Student("蜘蛛精",26,172.5);Student s3 = new Student("紫霞",23,167.6);Student s4 = new Student("白晶晶",25,169.0);Student s5 = new Student("牛魔王",35,183.3);Collection<Student> ls = new ArrayList<>();Collections.addAll(ls,s1,s2,s3,s4,s5);// 需求2:找出年龄大于等于23,且年龄小于等于30的学生,并按照年龄降序输出
// List<Student> st = ls.stream().filter(s ->s.getAge()>=23 && s.getAge()<=30).sorted(new Comparator<Student>() {
// @Override
// public int compare(Student o1, Student o2) {
// return o2.getAge()-o1.getAge();
// }
// }).collect(Collectors.toList());
// System.out.println(st);// 需求3:取出身高的前三3名学生,并输出
// ls.stream().sorted(new Comparator<Student>() {
// @Override
// public int compare(Student o1, Student o2) {
// return Double.compare(o2.getScore(),o1.getScore());
// }
// }).limit(3).forEach(s-> System.out.println(s));//需求4: 取出身高倒数的2名学生,并输出
// ls.stream().sorted((o1, o2) -> Double.compare(o2.getScore(),o1.getScore()))
// .skip(ls.size()- 2).forEach(s-> System.out.println(s));// 需求5 : 找出身高超出169的学生叫什么名字,要求去除重复的名字,再输出ls.stream().filter(s->s.getScore()>168).distinct().forEach(s-> System.out.println(s));}
}
终结方法
public class map11 {public static void main(String[] args) {Student s1 = new Student("蜘蛛精",26,172.5);Student s2 = new Student("蜘蛛精",26,172.5);Student s3 = new Student("紫霞",23,167.6);Student s4 = new Student("白晶晶",25,169.0);Student s5 = new Student("牛魔王",35,183.3);Collection<Student> ls = new ArrayList<>();Collections.addAll(ls,s1,s2,s3,s4,s5);// 需求1:请计算出身高超过168的学生有几个人long st = ls.stream().filter(s->s.getHeight()>168).count();System.out.println(st);// 需求2: 请找出身高最高的学生对象Optional<Student> s = ls.stream().max(( o1, o2) ->Double.compare(o1.getHeight() , o2.getHeight()));System.out.println(s);// 需求3 : 请找出身高超过170的学生对象,并返回一个新集合中List<Student> student1 = ls.stream().filter(m ->m.getHeight()>170).collect(Collectors.toList());System.out.println(student1);// 需求4 : 找出身高超过170的学生对象,并把学生对象名字和身高存到一个Map集合中Map<String,Double> m1 = ls.stream().filter(q->q.getHeight()>170).distinct().collect(Collectors.toMap(w->w.getName(),w->w.getHeight()));System.out.println(m1);}
}