可变参数
可变参数就是一种特殊形参,定义在方法、构造器的形参列表里,格式是:数据类型…参数名称;
可变参数的特点和好处
特点:可以不传数据给它;可以传一个或者同时传多个数据给它;也可以传一个数组给它。
好处:常常用来灵活的接收数据。
package com.itchinajie.d1_parameter;
import java.util.Arrays;
/*
*目标:认识可变参数,掌握其应用
* */
public class ParamTest {
public static void main(String[] args) {
//特点:
test();//不传数据
test(10);//传输一个数据给它
test(10,20,30);//传输多个数据给它
test(new int[] {10,20,30,40});//传输一个数组给可变参数
//注意事项1:一个形参列表中,只能有一个可变参数。
//注意事项2:可变参数必须放在形参列表的最后面
}
public static void test(int...nums){
//可变参数在方法内部,本质就是一个数组。
System.out.println(nums.length);
System.out.println(Arrays.toString(nums));
System.out.println("----------------------------");
}
}
可变参数的注意事项:
1、可变参数在方法内部就是一个数组。
2、一个形参列表中可变参数只能有一个。
3、可变参数必须放在形参列表的最后面。
Collections
Collections是一个用来操作集合的工具类。
Collections提供的常用的静态方法:
package com.itchinajie.d2_collections;
import java.util.Objects;
public class Student implements Comparable<Student>{
private String name;
private int age;
private double height;
//方式一:让自定义的类(如学生类)实现Comparable接口,重写里面的compareTo方法来指定比较规则。
@Override
public int compareTo(Student o) {
//约定1: 如果左边的对象 大于 右边对象 请您返回正整数
//约定2: 如果左边的对象 小于 右边对象 请您返回负整数
//约定3: 如果左边的对象 等于 右边对象 请您返回0
//按照年龄升序排序
// if (this.age > o.age) {
// return 1;
// }else if (this.age < o.age){
// return -1;
// }
// return 0;
//return this.age - o.age;//升序
return o.age - this.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 double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public Student() {
}
public Student(String name, int age, double height) {
this.name = name;
this.age = age;
this.height = height;
}
//只要两个对象内容一样就返回true
@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 && Double.compare(height, student.height) == 0 && Objects.equals(name, student.name);
}
//只要两个对象内容一样,返回的哈希值就是一样的。
@Override
public int hashCode() {
return Objects.hash(name, age, height);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", height=" + height +
'}';
}
}
package com.itchinajie.d2_collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*
*目标:掌握Collections集合工具的使用
* */
public class CollectionsTest1 {
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(5);
list.add(3);
list.add(2);
System.out.println(list);
//注意:本方法可以直接对自定义类型的List集合排序,但自定义类型必须实现了Comparable接口,指定了比较规则才可以。
List<Student> students = new ArrayList<>();
students.add(new Student("蜘蛛精",23,169.7));
students.add(new Student("紫霞",22,169.8));
students.add(new Student("紫霞",22,169.8));
students.add(new Student("牛魔王",22,183.5));
//以上如果Student类不继承Comparable接口来自定义排序就会报错
//或者用重载的sort方法,即使有自定义类型的对象,也可以申明一个Comparator比较器对象对他进行排序
//4、public static<T>void sort(List<T> List,Comparator.<? super T > c): 对List集合中元素,按照比较器对象指定的规则进行排序.
// Collections.sort(students, new Comparator<Student>() {
// @Override
// public int compare(Student o1, Student o2) {
// return Double.compare(o1.getHeight(), ,o2.getHeight());
// }
// });
Collections.sort(students,( o1, o2) -> Double.compare(o1.getHeight(),o2.getHeight()));
System.out.println(students);
}
}
Collections只能支持对List集合进行排序。
排序方式一:
注意:本方法可以直接对自定义类型的List集合排序,但自定义类型必须实现了Comparable接口,指定了比较规则才可以。
排序方式二:
斗地主游戏综合案例
1、做牌
1、创建GameDome类
2、创建Card类定义牌的基本数据昵称
3、创建Room类存储牌的数据
2、洗牌
1、在Room类中定义一个start方法用来洗牌、发牌
2、排序
3、看牌
完整案例
package com.itchinajie.d3_collection_test;
/**
目标: 斗地主游戏的案例开发。
业务需求分析:
业务:总共有54张牌。
点数: "3","4","5","6","7","8","9","10","J","Q","K","A","2"
花色: "♠", "♣", "♦", "❤"
大小王: "" ""
点数分别要组合4种花色,大小王各一张。
斗地主:发出51张牌,剩下3张作为底牌。
*/
public class GameDemo {
public static void main(String[] args) {
//1、牌类
//2、房间
Room m = new Room();
//3、启动游戏
m.start();
}
}
package com.itchinajie.d3_collection_test;
public class Card {
private String number;
private String color;
//每张牌是存在大小的。
@Override
public String toString() {
return number + color;
}
private int size;//0 1 2 ...
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public Card() {
}
public Card(String number, String color, int size) {
this.number = number;
this.color = color;
this.size = size;
}
}
package com.itchinajie.d3_collection_test;
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<>();
//1、做出54张牌,存入到集合allCards
//a、点数:个数确定了,类型确定。
public Room() {
String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
//b、花色:个数确定了,类型确定。
String[] colors = {"♠", "♣", "♦", "❤"};
int size = 0;//表示每张牌的大小
//c、遍历点数,再遍历花色,组织牌
for (String number : numbers) {
//number "3"
size++;//12..
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、洗牌:allCards;
Collections.shuffle(allCards);
System.out.println("洗牌后:"+allCards);
//2、发牌,首先定义三名玩家
//2、发牌,首先肯定要定义 三个玩家。List(ArrayList) Set(TreeSet)
List<Card> linHuChong = new ArrayList<>();
List<Card> jiuMoZhi = new ArrayList<>();
List<Card> renYingYing = new ArrayList<>();
//正式发牌给这三个玩家,依次发出51张牌,剩余3张做为底牌。
for(int i=0;i< allCards.size()-3;i++){
Card c = allCards.get(i);
//判断牌发给谁
if(i % 3 ==0){
//请啊冲接牌
linHuChong.add(c);
}else if(i % 3 ==1){
//请啊鸠来接牌
jiuMoZhi.add(c);
}else if(i % 3 ==2){
//请盈盈接牌
renYingYing.add(c);
}
}//
// 3、对三个人的牌的大小进行排序
sortCards(linHuChong);
sortCards(jiuMoZhi);
sortCards(renYingYing);
//4、看牌
System.out.println("啊冲:"+linHuChong);
System.out.println("啊鸠:"+jiuMoZhi);
System.out.println("盈盈:"+renYingYing);
List<Card> lastThreeCards = allCards.subList(allCards.size()-3,allCards.size());//51 52 53
System.out.println("底牌:"+lastThreeCards);
sortCards(jiuMoZhi);
jiuMoZhi.addAll(lastThreeCards);
System.out.println("啊鸠抢到地主后:"+jiuMoZhi);
}
/*
*综合排序
* */
private void sortCards(List<Card> cards){
Collections.sort(cards, (o1, o2) -> o1.getSize() - o2.getSize());//升序
}
}
Map系列集合
什么是Map集合?
1、Map集合称为双列集合,格式:{key1=value1,key2=value2,key3=value3,...},一次需要存一对 数据做为一个元素;
2、Map集合的每个元素"key=value”称为一个键值对/键值对对象/一个Entry对象,Map集合也 被叫做"键值对集合”;
3、Map集合的所有键是不允许重复的,但值可以重复,键和值是 一 一对应的,每一个键只 能找到自己对应的值。
Map集合体系
Map集合体系的特点
注意:Mp系列集合的特点都是由键决定的,值只是一个附属品,值是不做要求的。
HashMap(由键决定特点):无序、不重复、无索引;(用的最多)。
LinkedHashMap(由键决定特点):由键决定的特点:有序、不重复、无索引。
TreeMap(由键决定特点):按照大小默认升序排序、不重复、无索引。
package com.itchinajie.d4_map;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
/*
* 目标:掌握Map集合的特点
* */
public class MapTest1 {
public static void main(String[] args) {
//Map<String,Integer> map = new HashMap<>();//一行经典代码。按照键无序,不重复,无索引。
Map<String,Integer> map=new LinkedHashMap<>();//有序,不重复,无索引。
map.put("手表",100);
map.put("手表",220);//后面重复的数据会覆盖前面的数据(键)
map.put("手机",2);
map.put("Java",2);
map.put(null,null);
System.out.println(map);
Map<Integer,String> map1=new TreeMap<>();//可排序,不重复,无索引
map1.put(23,"Java");
map1.put(23,"MySQL");
map1.put(19,"李四");
map1.put(20,"王五");
System.out.println(map1);
}
}
Map的常用方法
Mp是双列集合的祖宗,它的功能是全部双列集合都可以继承过来使用的。
package com.itchinajie.d4_map;
import java.util.*;
/*
* 目标:掌握Map集合的特点
* */
public class MapTest2 {
public static void main(String[] args) {
Map<String,Integer> map=new HashMap<>();
map.put("手表",100);
map.put("手表",220);
map.put("手机",2);
map.put("Java",2);
map.put(null,null);
System.out.println(map);
//2.public int size():获取集合的大小
System.out.println(map.size());
//3、public void clear():清空集合
//map.clear();
//System.out.println(map);
//4.public boolean isEmpty():判断集合是否为空,为空返回trUe,反之!
System.out.println(map.isEmpty());
//5.public V get(Object key.): 根据键获取对应值
int v1 = map.get("手表");
System.out.println(v1);
System.out.println(map.get("手机")); //2
System.out.println(map.get("张三")); //null
//6.public V remove(Object key): 根据键删除整个元素(删除键会返回键的值)
System.out.println(map.remove("手表"));
System.out.println(map);
//7.public boolean containsKey(Object key.):判断是否包含某个键,包含返回true,
System.out.println(map.containsKey("手表"));//false
System.out.println(map.containsKey("手机"));//true
System.out.println(map.containsKey("java"));//false
System.out.println(map.containsKey("Java"));//true
//8.public boolean containsValue(Object valve): 判断是否包含某个值。
System.out.println(map.containsValue(2)); //true
System.out.println(map.containsValue("2")); //false
//9.public Set<K> keySet():获取Map集合的全部键。
Set<String> keys = map.keySet();
System.out.println(keys);
//10.public Collection<V> valves();获取Map集合的全部值。
Collection<Integer> values = map.values();
System.out.println(values);
//11.把其他Map集合的数据倒入到自己集合中来。(拓展)
Map<String,Integer> map1 = new HashMap<>();
map1.put("java1",10);
map1.put("java2",20);
Map<String,Integer> map2 = new HashMap<>();
map2.put("java3",1);
map2.put("java2",222);
map1.putAll(map2);//putAll:把map2集合中的元素全部倒入一份到map1集
System.out.println(map1);
System.out.println(map2);
}
}
Map集合的遍历方式
1、通过键找值遍历
先获取Map集合全部的键,再通过遍历键来找值。
需要用到的方法:
package com.itchinajie.d5_map_traverse;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 目标:掌握Map集合的遍历方式1:键找值
*/
public class MapTest1 {
public static void main(String[] args) {
//准备一个Map集合。
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={蜘蛛精=169,,牛魔王=183.6,至尊宝=169.5,紫霞=165.8}
//1、获取Map集合的全部键
Set<String> keys = map.keySet();
System.out.println(keys);
//2、遍历全部的键,根据键获取其对应的值
for (String key : keys){
//根据键获取对应的值
double value = map.get(key);
System.out.println(key + "=====>" + value);
}
}
}
2、通过键值对遍历
package com.itchinajie.d5_map_traverse;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 目标:掌握Map集合的遍历方式2:键值对
*/
public class MapTest2 {
public static void main(String[] args) {
//准备一个Map集合。
Map<String, Double> map = new HashMap<>();
map.put("蜘蛛精",169.8);
map.put("紫霞",165.8);
map.put("至尊宝",169.5);
map.put("牛魔王",183.6);
System.out.println(map);
//map = {蜘蛛精=169.8,牛魔王=183.6,至尊宝=169.5,紫霞=165.8}
//entries=[(蜘蛛精=169.8),(牛魔王=183.6),(至尊宝=169.5),(紫霞=165.8)]
// entry
//1、调用Map集合提供entrySet方法,把Map集合转换成键值对类型的Set集合
Set<Map.Entry<String,Double>>entries = map.entrySet();
for (Map.Entry<String,Double> entry : entries) {
String key = entry.getKey();
double value = entry.getValue();
System.out.println(key + "---->" + value);
}
}
}
3、通过Lambda表达式
package com.itchinajie.d5_map_traverse;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 目标:掌握Map集合的遍历方式3:Lambda表达式
*/
public class MapTest3 {
public static void main(String[] args) {
//准备一个Map集合。
Map<String, Double> map = new HashMap<>();
map.put("蜘蛛精",169.8);
map.put("紫霞",165.8);
map.put("至尊宝",169.5);
map.put("牛魔王",183.6);
System.out.println(map);
//map={蜘蛛精=169.8,牛魔王=183.6,至尊宝=169.5,紫霞=165.8}
map.forEach((k,v)->{
System.out.println(k +"--->"+v);
});
//map.forEach(new BiConsumer<string,Double>(){
//@verride
//public void accept(string k,Double v){
//System.out.println(k +"---->"+v);
//}
//});
map.forEach((k,v)->{
System.out.println(k +"---->"+v);
});
}
}
小案例
package com.itchinajie.d5_map_traverse;
import java.util.*;
/*
* 目标:完成Map集合的案例,统计投票人数
* */
public class MaoDemo4 {
public static void main(String[] args) {
//1、把80个学生选择的景点数据拿到程序中来
List<String> data = new ArrayList<>();
String[] selects = {"A","B","C","D"};
Random r = new Random();
for (int i = 1; i <= 80 ; i++) {
//每次模拟一个学生选择一个景点,存入到集合中去
int index = r.nextInt(4);
data.add(selects[index]);
}
System.out.println(data);
//2、开始统计每个景点的投票人数
//准备一个Map集合用于统计最终的结果
Map<String ,Integer> result = new HashMap<>();
//3、开始遍历80个景点数据
for (String s : data) {
//问问Map集合中是否存在该景点
if(result.containsKey(s)){
//说明这个景点之前统计过,其值+1,存到Map集合去
result.put(s,result.get(s) + 1);
}else{
//说明这个景点第一次存入景点= 1
result.put(s,1);
}
}
System.out.println(result);
}
}
HashMap
特点:由键决定特点,无序、不重复、无索引。
HashMap集合的底层原理
HashMap跟HashSet的底层原理是一模一样的,都是基于哈希表实现的。
1、HashMap集合是一种增删改查数据,性能都较好的集合;
2、但是它是无序,不能重复,没有索引支持的(由键决定特点);
3、HashMap的键依赖nashCode方法和equals方法保证键的唯一;
4、如果键存储的是自定义类型的对象,可以通过重写hashCode和equals方法,这样
可以保证多个对象内容一样时,HashMap集合就能认为是重复的。
实际上:原来学的Set系列集合的底层就是基于Map实现的,只是Set集合中的元素只要键数据,不要值数据而已。
哈希表
JDK8之前,哈希表=数组+链表
JDK8开始,哈希表=数组+链表+红黑树
哈希表是一种增删改查数据,性能都较好的数据结构。
package com.itchinajie.d6_map_impl;
import java.util.HashMap;
import java.util.Map;
/*
* 目标:掌握HashMap的特点
* */
public class Test1HashMap {
public static void main(String[] args) {
Map<Student,String> map = new HashMap<>();
map.put(new Student("蜘蛛精",25,168.5),"盘丝洞");
map.put(new Student("蜘蛛精",25,168.5),"水帘洞");
map.put(new Student("至尊宝",23,163.5),"水帘洞");
map.put(new Student("牛魔王",28,183.5),"牛头山");
System.out.println(map);
}
}
LinkedHashMap
特点:(由键决定)有序、不重复、无索引。
LinkedHashMap:集合的原理
底层数据结构依然是基于哈希表实现的,只是每个键值对元素又额外的多了一个双链表的机制记录元素顺序(保证有序)。
实际上:原来学习的LinkedHashSets集合的底层原理就是LinkedHashMap。
package com.itchinajie.d6_map_impl;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/*
* 目标:掌握LinkedHashMap的特点
* */
public class Test2LinkedHashMap {
public static void main(String[] args) {
Map<String,Integer> map = new LinkedHashMap<>(); //有序,不重复,无索引。
map.put("手表",100);
map.put("手表",220);//后面重复的数据会覆盖前面的数据(键)
map.put("手机",2);
map.put("Java",2);
map.put(null,null);
System.out.println(map);
}
}
TreeMap
特点:不重复、无索引、可排序(按照键的大小默认升序排序,只能对键排序)。
原理:TreeMap跟TreeSet集合的底层原理是一样的,都是基于红黑树实现的排序。
TreeMap集合同样也支持两种方式来指定排序规则
1、让类实现Comparable接口,重写比较规则。
2、TreeMap集合有一个有参数构造器,支持创建Comparatorl比较器对象,以便用来指定比较规则。
package com.itchinajie.d6_map_impl;
import java.util.*;
/*
* 目标:掌握TreeMap的特点
* */
public class Test3TreeMap {
public static void main(String[] args) {
Map<Student,String> map = new TreeMap<>((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight()));
map.put(new Student("蜘蛛精",25,168.5),"盘丝洞");
map.put(new Student("蜘蛛精",25,168.5),"水帘洞");
map.put(new Student("至尊宝",23,163.5),"水帘洞");
map.put(new Student("牛魔王",28,183.5),"牛头山");
System.out.println(map);
}
}
集合的嵌套
package com.itchinajie.d7_collection_nesting;
import java.util.*;
/**
目标:理解集合的嵌套。
*江苏省= "南京市",“扬州市","苏州市",“无锡市","常州市"
*湖北省="武汉市","孝感市","十堰市","宜昌市","鄂州市"
*河北省="石家庄市","唐山市",“邢台市",“保定市","张家口市"
*/
public class Test {
public static void main(String[] args) {
//1、定义一个Map集合存储全部的省份信息,和其他对应的城市信息
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);
List<String> cities3 = new ArrayList<>();
Collections.addAll(cities3,"石家庄市","唐山市","邢台市","保定市","张家口市");//批量添加元素的方法
map.put("河北省",cities3);
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);
});
}
}
JDK8新特性:Stream流
什么是Stream?
Steam也叫Stream流,是Jdk8开始新增的一套API (java.util.stream.*),可以用于操作集合或者数组的数据。
优势:Stream流大量的结合了Lambda的语法风格来编程,提供了一种更加强大,更加简单的方式操
作集合或者数组中的数据,代码更简洁,可读性更好。
package com.itchinajie.d8_stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*
* 目标:初步体验Stream流的方便与快捷
* */
public class StreamTest1 {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
Collections.addAll(names,"张三丰","张无忌","周若芷","赵敏","张强");
System.out.println(names);
//name = [张三丰,张无忌,周若芷,赵敏,张强]
//找出姓张,且是3个字的名字,存入到新集合中去
//1、常规方法
List<String> list = new ArrayList<>();
for (String name : names) {
if (name.startsWith("张") && name.length() == 3){
list.add(name);
}
}
System.out.println(list);
//Lambda表达式
List<String> list2 = names.stream().filter(s -> s.startsWith("张"))
.filter(a -> a.length() == 3).collect(Collectors.toList());
System.out.println(list2);
}
}
Stream流的使用步骤
Stream流的常用方法
获取Stream流
1、获取集合的Stream流
2、获取数组的Stream流
package com.itchinajie.d8_stream;
import java.util.*;
import java.util.stream.Stream;
public class StreamTest2 {
public static void main(String[] args) {
//1、如何获取List集合的Stream流
List<String> names = new ArrayList<>();
Collections.addAll(names,"张三丰","张无忌","周若芷","赵敏","张强");
Stream<String> stream = names.stream();
//2、如何获取Set集合的Stream流
Set<String> set = new HashSet<>();
Collections.addAll(set,"刘德华","张曼玉","蜘蛛精","玛德","德玛西亚");
Stream<String> stream1 = set.stream();
stream1.filter(s -> s.contains("德")).forEach(s -> System.out.println(s));
//3、如何获取Map集合的Stream流
Map<String,Double> map = new HashMap<>();
map.put("古力娜扎",172.3);
map.put("迪丽热巴",168.3);
map.put("马尔扎哈",166.3);
map.put("卡尔扎巴",168.3);
Set<String> keys = map.keySet();
Stream<String> ks = keys.stream();
Collection<Double> values = map.values();
Stream<Double> vs = values.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()));
//4、如何获取数组的Stream流
String[] names2 = {"张翠山","东方不败","唐大山","孤独求败"};
Stream<String> names3 = Arrays.stream(names2);
Stream<String> names4 = Stream.of(names2);
}
}
Stream流常见的中间方法
中间方法指的是调用完成后会返回新的Stream流,可以继续使用(支持链式编程)。
package com.itchinajie.d8_stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
/*
* 目标:掌握Stream流常见的中间方法
* */
public class StreamTest3 {
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,25.0);
//需求1:找出成绩大于等于60分的数据,并升序后,再输出
scores.stream().filter(s -> s >= 60).sorted().forEach(System.out::println);
List<Student> students = new ArrayList<>();
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);
Student s6 = new Student("牛夫人",34,168.5);
Collections.addAll(students,s1,s2,s3,s4,s5,s6);
//需求2:找出年龄大于等于23,且年龄小于等于30岁的学生,并按照年龄降序输出
students.stream().filter(student -> student.getAge() >= 23 && student.getAge() <= 30)
.sorted(((o1, o2) -> o1.getAge() - o2.getAge()))
.forEach(System.out::println);
//需求3:去除身高最高的3名学生,并输出
students.stream().sorted(((o1, o2) -> Double.compare(o2.getHeight(), o1.getHeight())))
.limit(3).forEach(System.out::println);
//需求4:去除身高倒数的2名学生,并输出
students.stream().sorted(((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight()))).limit(2)
.forEach(System.out::println);
students.stream().sorted(((o1, o2) -> Double.compare(o2.getHeight(), o1.getHeight())))
.skip(students.size() - 2).forEach(System.out::println);
//需求5:找出身高超过168的学生叫什么名字,要求去除重复的名字,再输出
students.stream().filter(student -> student.getHeight() >= 168).map(Student::getHeight)
.distinct().forEach(System.out::println);
//distinct去重复,自定义类型的对象(希望内容一样就认为重复,重写equals,hashcode方法)
students.stream().filter(student -> student.getHeight() > 168)
.distinct().forEach(System.out::println);
Stream<String> st1 = Stream.of("张三","李四");
Stream<String> st2 = Stream.of("张三1","李四2","王五");
Stream<String> allSt = Stream.concat(st1,st2);
allSt.forEach(System.out::println);
}
}
Stream流常见的终结方法
终结方法指的是调用完成后,不会返回新Stream了,没法继续使用流了。
package com.itchinajie.d8_stream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamTest4 {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
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);
Student s6=new Student("牛夫人",34,168.5);
Collections.addAll(students, s1, s2, s3, s4, s5, s6);
//需求1:请计算出身高超过168的学生有几人。
long size = students.stream().filter(student -> student.getHeight() > 168).count();
System.out.println(size);
//需求2:请找出身高最高的学生对象,并输出。
Student s = students.stream().max(((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight()))).get();
System.out.println(s);
//需求3:请找出身高最矮的学生对象,并输出。
Student ss = students.stream().min(((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight()))).get();
System.out.println(ss);
//需求4:请找出身高超过170的学生对象,并放到一个新集合中去返回。
//流只能收集一次
Stream<Student> studentStream = students.stream().filter(student -> student.getHeight() > 170);
List<Student> students1 = studentStream.collect(Collectors.toList());
System.out.println(students1);
Set<Student> students2 = students.stream().filter(student -> student.getHeight() > 170)
.collect(Collectors.toSet());
System.out.println(students2);
//需求5:请找出身高超过170的学生对象,并把学生对象的名字和身高,存入到一个Map集合返回
Map<String, Double> collect = students.stream().filter(student -> student.getHeight() > 170).distinct()
.collect(Collectors.toMap(a -> a.getName(), a -> a.getHeight()));
System.out.println(collect);
//Object[] array = students.stream().filter(student -> student.getHeight() > 170).toArray();
Student[] array = students.stream().filter(student -> student.getHeight() > 170).toArray(len -> new Student[len]);
System.out.println(Arrays.toString(array));
}
}
package com.itchinajie.d8_stream;
import java.util.Objects;
public class Student {
private String name;
private int age;
private double height;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", height=" + height +
'}';
}
@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 && Double.compare(height, student.height) == 0 && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, height);
}
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 getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public Student() {
}
public Student(String name, int age, double height) {
this.name = name;
this.age = age;
this.height = height;
}
}
收集Stream流
收集Stream流:就是把Stream流操作后的结果转回到集合或者数组中去返回。
Stream流:方便操作集合/数组的手段;集合/数组:才是开发中的目的。
(本章图片均来自于黑马程序员视频)