변경할 수 없는 컬렉션 만들기
불변 컬렉션이란?
- 변경할 수 없는 컬렉션은 수정할 수 없는 컬렉션입니다.
- 컬렉션의 데이터 항목은 생성 시 제공되며 전체 수명 동안 변경할 수 없습니다. 그렇지 않으면 오류를 보고하십시오
불변 컬렉션을 만드는 이유
- 특정 숫자를 수정할 수 없는 경우 예방적으로 변경할 수 없는 컬렉션에 복사하는 것이 좋습니다.
- 또는 컬렉션 개체가 신뢰할 수 있는 라이브러리 유틸리티가 아닌 경우 불변 형식이 안전합니다.
변경 불가능한 컬렉션을 만드는 방법
- List, Set 및 Map 인터페이스에는 불변 컬렉션을 생성할 수 있는 of 메서드가 있습니다.
public static void main(String[] args) {
//只需要对数据进行观看,并不需要修改数据
List<Double> lists= List.of(569.5,700.5,523.0,570.5);
//lists.add(12.0); 会报错 不可修改
System.out.println(lists);
//2.不可变的Set集合
Set<String> names= Set.of("迪丽热巴","迪丽热九");
System.out.println(names);
//2.不可变的Map集合
Map<String,Integer> maps= Map.of("迪丽热巴",1);
System.out.println(names);
}
개울
스트림이란?
목적: Lambda 표현식과 결합된 수집 및 배열 작업을 단순화하기 위한 API
public static void main(String[] args) {
List<String> names=new ArrayList<>();
Collections.addAll(names,"张小红","小敏","笑话","张敏","张涛");
System.out.println(names);
//1.从集合中找出姓张的放到新集合
List<String> zhanglist=new ArrayList<>();
for(String name:names){
if(name.startsWith("张")){
zhanglist.add(name);
}
}
System.out. println(zhanglist);
//名称长度为3的
List<String> zhangThreelist=new ArrayList<>();
for(String name:zhanglist){
if(name.length()==3){
zhangThreelist.add(name);
}
}
System.out.println(zhangThreelist);
그리고 Stream 한 줄의 코드를 사용하면
names.stream().filter(s ->s.startsWith("张")).filter(s ->s.length()==3).forEach(s -> System.out.println(s));
스트림 흐름 사고의 핵심:
- 먼저 컬렉션 또는 배열(즉, 컨베이어 벨트)의 스트림 스트림을 가져옵니다.
- 요소를 넣어
- 그런 다음 이 간소화된 API를 사용하여 요소를 편리하게 조작하십시오.
스트림 스트림 가져오기
스트림 스트림 가져오기
- 파이프라인을 생성하고 파이프라인에 데이터를 넣어 운영 준비
중급 방법 - 파이프라인 작업. 하나의 작업이 완료되면 다른 작업을 계속 수행할 수 있습니다
. - Stream은 파이프라인의 마지막 작업인 하나의 종료 방법만 가질 수 있습니다.Stream
작업 컬렉션 또는 배열의 첫 번째 단계는 먼저 Stream을 얻은 다음
Stream의 함수 집합을 사용하여 Stream을 얻는 것입니다. - Collaboration 인터페이스에서 기본 메서드 stream()을 사용하여 스트림
배열을 생성하여 스트림 스트림을 얻을 수 있습니다.
//Collection集合获取流
Collection<String> list=new ArrayList<>();
Stream<String> s=list.stream();
//Map集合获取流
Map<String,Integer> maps=new HashMap<>();
//键流
Stream<String> keyStream=maps.keySet().stream();
//值流
Stream<Integer> valueStream=maps.values().stream();
//键值对流(拿整体)
Stream<Map.Entry<String,Integer>> keyAndValueStream=maps.entrySet().stream();
//数组获取流
String[] names={
"赵敏","小昭","灭绝","周芷若"};
//拿到Stream流方法一
Stream<String> nameStream= Arrays.stream(names);
//方法二
Stream<String> nameStream2=Stream.of(names);
스트림 공통 API(중간 연산 방식)
- 중간 방법은 비종단 방법이라고도 하며 호출이 완료된 후 반환된 Stream을 계속 사용할 수 있으며 체인 프로그래밍이 지원됩니다.
- 컬렉션 및 배열의 데이터는 Stream에서 직접 수정할 수 없습니다.
Stream의 일반적인 터미널 작업 방법
참고: 작업 메서드가 종료된 후에는 스트림이 반환되지 않으므로 호출이 완료된 후 스트림을 사용할 수 없습니다.
스트림의 포괄적인 적용
package com.itheima.stream_test;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class StreamDemo04 {
public static double allMoney ;
public static double allMoney2 ; // 2个部门去掉最高工资,最低工资的总和
public static void main(String[] args) {
List<Employee> one = new ArrayList<>();
one.add(new Employee("猪八戒",'男',30000 , 25000, null));
one.add(new Employee("孙悟空",'男',25000 , 1000, "顶撞上司"));
one.add(new Employee("沙僧",'男',20000 , 20000, null));
one.add(new Employee("小白龙",'男',20000 , 25000, null));
List<Employee> two = new ArrayList<>();
two.add(new Employee("武松",'男',15000 , 9000, null));
two.add(new Employee("李逵",'男',20000 , 10000, null));
two.add(new Employee("西门庆",'男',50000 , 100000, "被打"));
two.add(new Employee("潘金莲",'女',3500 , 1000, "被打"));
two.add(new Employee("武大郎",'女',20000 , 0, "下毒"));
// 1、开发一部的最高工资的员工。(API)
// 指定大小规则了
// Employee e = one.stream().max((e1, e2) -> Double.compare(e1.getSalary() + e1.getBonus(), e2.getSalary() + e2.getBonus()))
// .get();
// System.out.println(e);
Topperformer t = one.stream().max((e1, e2) -> Double.compare(e1.getSalary() + e1.getBonus(), e2.getSalary() + e2.getBonus()))
.map(e -> new Topperformer(e.getName(), e.getSalary() + e.getBonus())).get();
System.out.println(t);
// 2、统计平均工资,去掉最高工资和最低工资
one.stream().sorted((e1, e2) -> Double.compare(e1.getSalary() + e1.getBonus(), e2.getSalary() + e2.getBonus()))
.skip(1).limit(one.size() - 2).forEach(e -> {
// 求出总和:剩余员工的工资总和
allMoney += (e.getSalary() + e.getBonus());
});
System.out.println("开发一部的平均工资是:" + allMoney / (one.size() - 2));
// 3、合并2个集合流,再统计
Stream<Employee> s1 = one.stream();
Stream<Employee> s2 = two.stream();
Stream<Employee> s3 = Stream.concat(s1 , s2);
s3.sorted((e1, e2) -> Double.compare(e1.getSalary() + e1.getBonus(), e2.getSalary() + e2.getBonus()))
.skip(1).limit(one.size() + two.size() - 2).forEach(e -> {
// 求出总和:剩余员工的工资总和
allMoney2 += (e.getSalary() + e.getBonus());
});
// BigDecimal
BigDecimal a = BigDecimal.valueOf(allMoney2);
BigDecimal b = BigDecimal.valueOf(one.size() + two.size() - 2);
System.out.println("开发部的平均工资是:" + a.divide(b,2, RoundingMode.HALF_UP));
}
}
package com.itheima.stream_test;
public class Employee {
private String name;
private char sex;
private double salary;
private double bonus;
private String punish; // 处罚信息
public Employee(){
}
public Employee(String name, char sex, double salary, double bonus, String punish) {
this.name = name;
this.sex = sex;
this.salary = salary;
this.bonus = bonus;
this.punish = punish;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
public String getPunish() {
return punish;
}
public void setPunish(String punish) {
this.punish = punish;
}
public double getTotalSalay(){
return salary * 12 + bonus;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", sex=" + sex +
", salary=" + salary +
", bonus=" + bonus +
", punish='" + punish + '\'' +
'}'+"\n";
}
}
package com.itheima.stream_test;
public class Topperformer {
private String name;
private double money; // 月薪
public Topperformer() {
}
public Topperformer(String name, double money) {
this.name = name;
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
@Override
public String toString() {
return "Topperformer{" +
"name='" + name + '\'' +
", money=" + money +
'}';
}
}