当前位置: 首页 > news >正文

Lambda 表达式练习

目录

sorted() 四种排序

List 转 Map

map 映射

对象中 String 类型属性为空的字段赋值为 null

BiConsumer,>

T reduce(T identity, BinaryOperator accumulator)

allMatch(Predicate p)

groupingBy(Function f)

flatMap(Function f)

Optional.ofNullable(T t) 和 T orElse(T other)


先来写个基本类

public class LambdaTest {@Dataclass Student {private Integer id;private String name;private Integer age;public Student(Integer id, String name, Integer age) {this.id = id;this.name = name;this.age = age;}}public List<Student> getStudents() {List<Student> list = new ArrayList<>();list.add(new Student(100, "小明", 10));list.add(new Student(101, "小红", 11));list.add(new Student(102, "小李", 12));list.add(new Student(103, "小王", 13));list.add(new Student(104, "小张", 14));list.add(new Student(105, "小五", 15));list.add(new Student(106, "小华", 16));return list;}
}

sorted() 四种排序

@Test
public void sortedTest() {List<Student> students = this.getStudents();//正序:常规写法List<Student> collect = students.stream().sorted((a1, a2) -> Integer.compare(a1.getAge(), a2.getAge())).collect(Collectors.toList());collect.forEach(System.out::println);System.out.println();//正序:lambda 简写List<Student> collectComparator = students.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());collectComparator.forEach(System.out::println);System.out.println();//倒序:常规写法List<Student> collectReversed = students.stream().sorted((a1, a2) -> Integer.compare(a2.getAge(), a1.getAge())).collect(Collectors.toList());collectReversed.forEach(System.out::println);System.out.println();//正序:lambda 简写List<Student> collectComparatorReversed = students.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());collectComparatorReversed.forEach(System.out::println);
}

List 转 Map

@Test
public void listToMapTest() {List<Student> students = this.getStudents();Map<Integer, Student> collect = students.stream().collect(Collectors.toMap(Student::getId, s -> s, (s1, s2) -> s1));collect.keySet().forEach(key -> System.out.println(String.format("key:%s,value:%s", key, collect.get(key))));
}

map 映射

 @Testpublic void mapTest() {List<Student> students = this.getStudents();
//        List<Student> students = Lists.newArrayList(new Student(null, "小炎姬", 5));Integer id = students.stream().map(Student::getId).max(Integer::compareTo).orElse(0);System.out.println(id);}

对象中 String 类型属性为空的字段赋值为 null

public static <T> void stringEmptyToNull(T t) {Class<?> clazz = t.getClass();Field[] fields = clazz.getDeclaredFields();Arrays.stream(fields).filter(f -> f.getType() == String.class).filter(f -> {try {f.setAccessible(true);String value = (String) f.get(t);return StringUtils.isEmpty(value);} catch (Exception ignore) {return false;}}).forEach(field -> {try {field.setAccessible(true);field.set(t, null);} catch (Exception ignore) {}});
}

BiConsumer<T, U>

<!-- lombok -->
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version>
</dependency><!-- guava -->
<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>28.2-jre</version>
</dependency>
/*** @author vincent*/
public class LambdaTest {@Dataprivate static class Student {private Integer id;private String name;private Integer age;private Integer interestType;private List<Hobby> hobbies;private List<Fancy> fancies;private Subject subject;private Student(Integer id, String name, Integer age, Integer interestType, List<Hobby> hobbies, List<Fancy> fancies, Subject subject) {this.id = id;this.name = name;this.age = age;this.interestType = interestType;this.hobbies = hobbies;this.fancies = fancies;this.subject = subject;}}enum InterestType {HOBBY(1, "兴趣"),FANCY(2, "喜好");private Integer code;private String message;InterestType(Integer code, String message) {this.code = code;this.message = message;}public Integer getCode() {return code;}public static InterestType getInterestTypeByCode(int code) {return Arrays.stream(InterestType.values()).filter(interestType -> interestType.getCode() == code).findFirst().orElse(null);}}@Dataprivate static class Hobby {private String basketball;private String running;private String drinking;private Hobby(String basketball, String running, String drinking) {this.basketball = basketball;this.running = running;this.drinking = drinking;}}@Dataprivate static class Fancy {private String dance;private String takePhotos;private String meetGirls;private Fancy(String dance, String takePhotos, String meetGirls) {this.dance = dance;this.takePhotos = takePhotos;this.meetGirls = meetGirls;}}@Dataprivate static class Subject {private String english;private String chinese;private String mathematics;private Subject(String english, String chinese, String mathematics) {this.english = english;this.chinese = chinese;this.mathematics = mathematics;}}private List<Student> getStudent() {List<Student> list = Lists.newArrayList();list.add(new Student(100, "小明", 10, 1,Lists.newArrayList(new Hobby("篮球", "跑步", "喝酒"),new Hobby("篮球_1", "跑步_1", "喝酒_1"),new Hobby("篮球_2", "跑步_2", "喝酒_2"),new Hobby("篮球_3", "跑步_3", "喝酒_3")),Lists.newArrayList(new Fancy("街舞", "摄影", "泡妞"),new Fancy("街舞_1", "摄影_1", "泡妞_1"),new Fancy("街舞_2", "摄影_2", "泡妞_2"),new Fancy("街舞_3", "摄影_3", "泡妞_3")),new Subject("英语", "语文", "数学")));list.add(new Student(200, "小红", 10, 2,Lists.newArrayList(new Hobby("篮球", "跑步", "喝酒"),new Hobby("篮球_1", "跑步_1", "喝酒_1"),new Hobby("篮球_2", "跑步_2", "喝酒_2"),new Hobby("篮球_3", "跑步_3", "喝酒_3")),Lists.newArrayList(new Fancy("街舞", "摄影", "泡妞"),new Fancy("街舞_1", "摄影_1", "泡妞_1"),new Fancy("街舞_2", "摄影_2", "泡妞_2"),new Fancy("街舞_3", "摄影_3", "泡妞_3")),new Subject("英语", "语文", "数学")));return list;}@Dataprivate static class Person {private Integer pid;private String pname;private Integer page;private String interest;private String subject;}private final static BiConsumer<Person, Student> HOBBY = (person, student) -> {Optional.ofNullable(student.getHobbies()).flatMap(hobbies -> hobbies.stream().findFirst()).ifPresent(hobby -> person.setInterest(hobby.getDrinking()));Optional.ofNullable(student.subject).ifPresent(subject -> person.setSubject(subject.getEnglish()));};private final static BiConsumer<Person, Student> FANCY = (person, student) -> {Optional.ofNullable(student.getFancies()).flatMap(fancies -> fancies.stream().findFirst()).ifPresent(fancy -> person.setInterest(fancy.getDance()));Optional.ofNullable(student.subject).ifPresent(subject -> person.setSubject(subject.getMathematics()));};private final static ImmutableMap<InterestType, BiConsumer<Person, Student>> OF = ImmutableMap.of(InterestType.HOBBY, HOBBY,InterestType.FANCY, FANCY);/*** BiConsumer<T, U> 实例*/@Testpublic void t() {List<Student> studentList = getStudent();List<Object> collect = studentList.stream().map(student -> {Person person = new Person();Optional.ofNullable(student).ifPresent(stu -> {person.setPid(stu.getId());person.setPname(stu.getName());person.setPage(stu.getAge());Integer interestType = student.getInterestType();InterestType interestTypeByCode = InterestType.getInterestTypeByCode(interestType);person.setInterest(interestTypeByCode.message);OF.get(interestTypeByCode).accept(person, student);});return person;}).collect(Collectors.toList());System.out.println(collect);}
}

T reduce(T identity, BinaryOperator<T> accumulator)

<!-- commons-lang3 -->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.9</version>
</dependency>

/*** @author qfxl*/
public class LambdaTest {@Dataprivate static class trip {private String departure;private String destination;private trip(String departure, String destination) {this.departure = departure;this.destination = destination;}}/*** reduce 规则:* 例子:1.上海 -> 北京*      2.北京 -> 上海*      3.天津 -> 西安*      4.拉萨 -> 灵芝*      5.灵芝 -> 兰州*      6.兰州 -> 西宁* 展示效果:上海-北京-上海,天津-西安,拉萨-灵芝-兰州-西宁*/private static final BinaryOperator<String> ACCUMULATOR = (v1, v2) -> {if (StringUtils.isEmpty(v1)) {return v2;}String[] item = StringUtils.split(v1, ",");String[] lastOfItem = StringUtils.split(item[item.length - 1], "-");String lastElement = lastOfItem[lastOfItem.length - 1];String[] nextItem = StringUtils.split(v2, "-");String startElement = nextItem[0];if (StringUtils.equals(lastElement, startElement)) {return v1 + "-" + nextItem[nextItem.length - 1];}return v1 + "," + v2;};@Testpublic void t2() {List<trip> list = Lists.newArrayList(new trip("上海", "北京"),new trip("北京", "上海"),new trip("天津", "西安"),new trip("拉萨", "灵芝"),new trip("灵芝", "兰州"),new trip("兰州", "西宁"));//[上海-北京-上海,天津-西安,拉萨-灵芝-兰州-西宁]String reduce = list.stream().map(t -> String.format("%s-%s", t.getDeparture(), t.getDestination())).reduce("", ACCUMULATOR);System.out.println(reduce);}
}

allMatch(Predicate p)

public static final String YYYYMMDD = "yyyyMMdd";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY__MM__DD = "yyyy/MM/dd";
public static final String YYYY__MM__DD_HH_MM = "yyyy/MM/dd HH:mm";
public static final String YYYY__MM__DD_HH_MM_SS = "yyyy/MM/dd HH:mm:ss";@Test
public void t3() {@Dataclass DateValidate {private String date;private String dateFormat;public DateValidate(String date, String dateFormat) {this.date = date;this.dateFormat = dateFormat;}}List<DateValidate> list = Lists.newArrayList(new DateValidate("202086", YYYYMMDD),new DateValidate("2020086", YYYYMMDD),new DateValidate("2020806", YYYYMMDD),new DateValidate("20200806", YYYYMMDD),new DateValidate("20200806 19", null),new DateValidate("20200806 19:00", null),new DateValidate("20200806 19:00:00", null),new DateValidate("2020-8-06", YYYY_MM_DD),new DateValidate("2020-08-6", YYYY_MM_DD),new DateValidate("2020-08-06", YYYY_MM_DD),new DateValidate("2020-08-06 19", null),new DateValidate("2020-08-06 19:00", YYYY_MM_DD_HH_MM),new DateValidate("2020-08-06 19:00:00", YYYY_MM_DD_HH_MM_SS),new DateValidate("2020/8/06", YYYY__MM__DD),new DateValidate("2020/08/6", YYYY__MM__DD),new DateValidate("2020/08/06", YYYY__MM__DD),new DateValidate("2020/08/06 19", null),new DateValidate("2020/08/06 19:00", YYYY__MM__DD_HH_MM),new DateValidate("2020/08/06 19:00:00", YYYY__MM__DD_HH_MM_SS));list.forEach(item -> {boolean matchDateTime = matchDateTime(item.getDate());System.out.println(item.getDate() + " (" + item.getDateFormat() + "):matchDateTime -> " + matchDateTime);});
}/*** 时间校验* @param dateTime* @return*/
public static boolean matchDateTime(String dateTime) {if (StringUtils.isEmpty(dateTime)) {return false;}String[] dt = dateTime.split("\\s+");if (dt.length == 1) {return dateMatch(dt[0], "/") || dateMatch(dt[0], "-");} else {String date = dt[0];String time = dt[1];return (dateMatch(date, "/") || dateMatch(date, "-")) && timeMatch(time, ":");}
}private static boolean timeMatch(String s, String split) {if (StringUtils.isEmpty(s)) {return true;}s = StringUtils.trim(s);String[] time = StringUtils.split(s, split);boolean isNumber = Arrays.stream(time).anyMatch(StringUtils::isNumeric);if (!isNumber) {return false;}if (time.length != 3) {return false;}if (time[0].length() > 2 || Integer.parseInt(time[0]) > 24) {return false;}if (time[1].length() > 2 || Integer.parseInt(time[1]) > 60) {return false;}if (time[2].length() > 2 || Integer.parseInt(time[2]) > 60) {return false;}return true;
}private static boolean dateMatch(String s, String spl) {if (StringUtils.isEmpty(s)) {return false;}s = StringUtils.trim(s);String[] date = StringUtils.split(s, spl);boolean isNumber = Arrays.stream(date).anyMatch(StringUtils::isNumeric);if (!isNumber) {return false;}if (date.length != 3) {return false;}if (date[0].length() != 4) {return false;}if (Integer.parseInt(date[1]) > 12) {return false;}if (Integer.parseInt(date[2]) > 31) {return false;}return true;
}

显示结果

202086 (yyyyMMdd):matchDateTime -> false
2020086 (yyyyMMdd):matchDateTime -> false
2020806 (yyyyMMdd):matchDateTime -> false
20200806 (yyyyMMdd):matchDateTime -> false
20200806 19 (null):matchDateTime -> false
20200806 19:00 (null):matchDateTime -> false
20200806 19:00:00 (null):matchDateTime -> false
2020-8-06 (yyyy-MM-dd):matchDateTime -> true
2020-08-6 (yyyy-MM-dd):matchDateTime -> true
2020-08-06 (yyyy-MM-dd):matchDateTime -> true
2020-08-06 19 (null):matchDateTime -> false
2020-08-06 19:00 (yyyy-MM-dd HH:mm):matchDateTime -> false
2020-08-06 19:00:00 (yyyy-MM-dd HH:mm:ss):matchDateTime -> true
2020/8/06 (yyyy/MM/dd):matchDateTime -> true
2020/08/6 (yyyy/MM/dd):matchDateTime -> true
2020/08/06 (yyyy/MM/dd):matchDateTime -> true
2020/08/06 19 (null):matchDateTime -> false
2020/08/06 19:00 (yyyy/MM/dd HH:mm):matchDateTime -> false
2020/08/06 19:00:00 (yyyy/MM/dd HH:mm:ss):matchDateTime -> true

groupingBy(Function f)

@Test
public void t5() {@Dataclass Stu {private Integer id;private String name;private Long money;public Stu(Integer id, String name, Long money) {this.id = id;this.name = name;this.money = money;}}List<Stu> list = Lists.newArrayList(new Stu(1, "小明", 100L),new Stu(1, "小红", 200L),new Stu(2, "小黄", 200L),new Stu(2, "小紫", 200L));Map<Integer, List<Stu>> collect = list.stream().collect(Collectors.groupingBy(Stu::getId));System.out.println(JSON.toJSONString(collect, SerializerFeature.PrettyFormat));
}

显示结果

{1:[{"id":1,"money":100,"name":"小明"},{"id":1,"money":200,"name":"小红"}],2:[{"id":2,"money":200,"name":"小黄"},{"id":2,"money":200,"name":"小紫"}]
}

flatMap(Function f)

@Data
private static class TravelInfo {private String trip;private String hotelName;private List<Order> orders;public TravelInfo(String trip, String hotelName, List<Order> orders) {this.trip = trip;this.hotelName = hotelName;this.orders = orders;}
}@Data
private static class Order {private Long orderId;private List<Travellers> travellers;public Order(Long orderId, List<Travellers> travellers) {this.orderId = orderId;this.travellers = travellers;}
}@Data
private static class Travellers {private String userName;private String email;public Travellers() {}public Travellers(String userName, String email) {this.userName = userName;this.email = email;}
}/*** flatMap(Function f):扁平化*/
@Test
public void t5() {TravelInfo travelInfo = new TravelInfo("三人行", "天上人间",Lists.newArrayList(new Order(123456789L, Lists.newArrayList(new Travellers("zhangSanFirst", "zhangSanFirst@qq.com"),new Travellers("zhangSanSecond", "zhangSanSecond@qq.com"))),new Order(987654321L, Lists.newArrayList(new Travellers("liSiFirst", "zhangSanFirst@qq.com"),new Travellers("liSiSecond", "zhangSanSecond@qq.com"))),new Order(987654322L, Lists.newArrayList(new Travellers("wangWu", "wangWu@qq.com"))),new Order(987654323L, Lists.newArrayList()),new Order(987654323L, null)));System.out.println(JSON.toJSONString(travelInfo, SerializerFeature.PrettyFormat));System.out.println();List<String> email = travelInfo.getOrders().stream().filter(Objects::nonNull).map(Order::getTravellers).filter(CollectionUtils::isNotEmpty).flatMap(Collection::stream).filter(Objects::nonNull).map(Travellers::getEmail).collect(Collectors.toList());System.out.println(email);
}

显示结果

{"hotelName":"天上人间","orders":[{"orderId":123456789,"travellers":[{"email":"zhangSanFirst@qq.com","userName":"zhangSanFirst"},{"email":"zhangSanSecond@qq.com","userName":"zhangSanSecond"}]},{"orderId":987654321,"travellers":[{"email":"zhangSanFirst@qq.com","userName":"liSiFirst"},{"email":"zhangSanSecond@qq.com","userName":"liSiSecond"}]},{"orderId":987654322,"travellers":[{"email":"wangWu@qq.com","userName":"wangWu"}]},{"orderId":987654323,"travellers":[]},{"orderId":987654323}],"trip":"三人行"
}[zhangSanFirst@qq.com, zhangSanSecond@qq.com, zhangSanFirst@qq.com, zhangSanSecond@qq.com, wangWu@qq.com]

Optional.ofNullable(T t) 和 T orElse(T other)

@Data
private class PaymentDto {private Long id;private String liqAccountName;/*** 来款业务:COMPANY-企业来款;OFFLINE-订单线下收款*/private String paymentMode;private List<ClaimDto> claimDto;private List<OrderClaimDto> orderClaimDto;public PaymentDto(Long id, String liqAccountName, String paymentMode, List<ClaimDto> claimDto, List<OrderClaimDto> orderClaimDto) {this.id = id;this.liqAccountName = liqAccountName;this.paymentMode = paymentMode;this.claimDto = claimDto;this.orderClaimDto = orderClaimDto;}
}@Data
private static class ClaimDto {private Long paymentId;private String partnerName;private Integer amount;public ClaimDto(Long paymentId, String partnerName, Integer amount) {this.paymentId = paymentId;this.partnerName = partnerName;this.amount = amount;}
}@Data
private static class OrderClaimDto {private Long paymentId;private Integer amount;public OrderClaimDto(Long paymentId, Integer amount) {this.paymentId = paymentId;this.amount = amount;}
}@Data
private static class PaymentApiDto {private Long id;private String liqAccountName;private String paymentMode;private Long paymentId;private String partnerName;private Integer amount;
}private List<PaymentDto> getPaymentDto() {List<PaymentDto> list = Lists.newArrayList();list.add(new PaymentDto(123456789L, "收款账户_COMPANY", "COMPANY",Lists.newArrayList(new ClaimDto(123456789L, "企业名称1", 999),new ClaimDto(123456789L, "企业名称2", 888),new ClaimDto(123456789L, "企业名称3", 777)),Lists.newArrayList(new OrderClaimDto(123456789L, 666),new OrderClaimDto(123456789L, 555))));list.add(new PaymentDto(987654321L, "收款账户_OFFLINE", "OFFLINE",Lists.newArrayList(new ClaimDto(987654321L, "企业名称1", 999),new ClaimDto(987654321L, "企业名称2", 888)),Lists.newArrayList(new OrderClaimDto(987654321L, 666),new OrderClaimDto(987654321L, 555))));list.add(new PaymentDto(888888888L, "收款账户", null, null, null));return list;
}/*** Optional.ofNullable(T t) 和 T orElse(T other)*/
@Test
public void t6() {List<PaymentDto> paymentDtos = getPaymentDto();paymentDtos.forEach(System.out::println);System.out.println();/*** 根据 paymentMode 把 claimDto、orderClaimDto 集合数据查分为单条数据*/List<PaymentApiDto> collect = paymentDtos.stream().map(paymentDto -> {PaymentApiDto apiDto = new PaymentApiDto();apiDto.setId(paymentDto.getId());apiDto.setLiqAccountName(paymentDto.getLiqAccountName());apiDto.setPaymentMode(paymentDto.getPaymentMode());ImmutableList<PaymentApiDto> defaultList = ImmutableList.of(apiDto);if (StringUtils.equals(paymentDto.getPaymentMode(), "COMPANY")) {return Optional.ofNullable(paymentDto.getClaimDto()).map(claimDtos -> claimDtos.stream().map(claimDto -> {PaymentApiDto paymentApiDto = new PaymentApiDto();paymentApiDto.setId(paymentDto.getId());paymentApiDto.setLiqAccountName(paymentDto.getLiqAccountName());paymentApiDto.setPaymentMode(paymentDto.getPaymentMode());paymentApiDto.setPaymentId(claimDto.getPaymentId());paymentApiDto.setPartnerName(claimDto.getPartnerName());paymentApiDto.setAmount(claimDto.getAmount());return paymentApiDto;}).collect(Collectors.toList())).orElse(defaultList);}if (StringUtils.equals(paymentDto.getPaymentMode(), "OFFLINE")) {return Optional.ofNullable(paymentDto.getOrderClaimDto()).map(orderClaimDtos -> orderClaimDtos.stream().map(orderClaimDto -> {PaymentApiDto paymentApiDto = new PaymentApiDto();paymentApiDto.setId(paymentDto.getId());paymentApiDto.setLiqAccountName(paymentDto.getLiqAccountName());paymentApiDto.setPaymentMode(paymentDto.getPaymentMode());paymentApiDto.setAmount(orderClaimDto.getAmount());return paymentApiDto;}).collect(Collectors.toList())).orElse(defaultList);}return defaultList;}).flatMap(Collection::stream).collect(Collectors.toList());collect.forEach(System.out::println);
}

显示结果

LambdaTest.PaymentDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, claimDto=[LambdaTest.ClaimDto(paymentId=123456789, partnerName=企业名称1, amount=999), LambdaTest.ClaimDto(paymentId=123456789, partnerName=企业名称2, amount=888), LambdaTest.ClaimDto(paymentId=123456789, partnerName=企业名称3, amount=777)], orderClaimDto=[LambdaTest.OrderClaimDto(paymentId=123456789, amount=666), LambdaTest.OrderClaimDto(paymentId=123456789, amount=555)])
LambdaTest.PaymentDto(id=987654321, liqAccountName=收款账户_OFFLINE, paymentMode=OFFLINE, claimDto=[LambdaTest.ClaimDto(paymentId=987654321, partnerName=企业名称1, amount=999), LambdaTest.ClaimDto(paymentId=987654321, partnerName=企业名称2, amount=888)], orderClaimDto=[LambdaTest.OrderClaimDto(paymentId=987654321, amount=666), LambdaTest.OrderClaimDto(paymentId=987654321, amount=555)])
LambdaTest.PaymentDto(id=888888888, liqAccountName=收款账户, paymentMode=null, claimDto=null, orderClaimDto=null)LambdaTest.PaymentApiDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, paymentId=123456789, partnerName=企业名称1, amount=999)
LambdaTest.PaymentApiDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, paymentId=123456789, partnerName=企业名称2, amount=888)
LambdaTest.PaymentApiDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, paymentId=123456789, partnerName=企业名称3, amount=777)
LambdaTest.PaymentApiDto(id=987654321, liqAccountName=收款账户_OFFLINE, paymentMode=OFFLINE, paymentId=null, partnerName=null, amount=666)
LambdaTest.PaymentApiDto(id=987654321, liqAccountName=收款账户_OFFLINE, paymentMode=OFFLINE, paymentId=null, partnerName=null, amount=555)
LambdaTest.PaymentApiDto(id=888888888, liqAccountName=收款账户, paymentMode=null, paymentId=null, partnerName=null, amount=null)

相关文章:

Lambda 表达式练习

目录 sorted() 四种排序 List 转 Map map 映射 对象中 String 类型属性为空的字段赋值为 null BiConsumer,> T reduce(T identity, BinaryOperator accumulator) allMatch(Predicate p) groupingBy(Function f) flatMap(Function f) Optional.ofNullable(T t) 和 …...

JavaScript第七讲:数组,及练习题

目录 今天话不多说直接进入正题&#xff01; 1. 创建数组对象 2. 数组长度 3. 遍历一个数组 4. 连接数组 5. 通过指定分隔符&#xff0c;返回一个数组的字符串表达 6. 分别在最后的位置插入数据和获取数据(获取后删除) 7. 分别在最开始的位置插入数据和获取数据(获取后删…...

从docker镜像反推Dockerfile

在项目运维的过程中&#xff0c;偶尔会遇到某个docker image打包时候的Dockerfile版本管理不善无法与image对应的问题&#xff0c;抑或需要分析某个三方docker image的构建过程&#xff0c;这时&#xff0c;就希望能够通过image反推构建时的instruction. 想实现这个过程可以使…...

车载软件架构 - AUTOSAR 的信息安全框架

车载软件架构 - AUTOSAR 的信息安全架构 我是穿拖鞋的汉子&#xff0c;魔都中坚持长期主义的汽车电子工程师。 老规矩&#xff0c;分享一段喜欢的文字&#xff0c;避免自己成为高知识低文化的工程师&#xff1a; 屏蔽力是信息过载时代一个人的特殊竞争力&#xff0c;任何消耗…...

欧洲版“OpenAI”——Mistral 举办的 AI 大模型马拉松

近期&#xff0c;法国的 Mistral AI 举办了一场别开生面的 AI 大模型马拉松。要知道&#xff0c;Mistral 可是法国对 OpenAI 的有力回应&#xff0c;而且其技术还是完全开源的呢&#xff01;这场在巴黎举行的黑客马拉松&#xff0c;规模空前盛大&#xff0c;竟然有超过 1000 名…...

Java | Leetcode Java题解之第128题最长连续序列

题目&#xff1a; 题解&#xff1a; class Solution {public int longestConsecutive(int[] nums) {Set<Integer> num_set new HashSet<Integer>();for (int num : nums) {num_set.add(num);}int longestStreak 0;for (int num : num_set) {if (!num_set.contai…...

C++的List

List的使用 构造 与vector的区别 与vector的区别在于不支持 [ ] 由于链表的物理结构不连续,所以只能用迭代器访问 vector可以排序,list不能排序(因为快排的底层需要随机迭代器,而链表是双向迭代器) (算法库里的排序不支持)(需要单独的排序) list存在vector不支持的功能 链…...

网易有道QAnything使用CPU模式和openAI接口安装部署

网易有道QAnything可以使用本地部署大模型&#xff08;官网例子为qwen&#xff09;也可以使用大模型接口(OPENAI或者其他大模型AI接口 )的方式&#xff0c;使用在线大模型API接口好处就是不需要太高的硬件配置。 本机环境windows11 首先安装WSL环境, 安装方法参考https://zhuan…...

量子加速超级计算简介

本文转载自&#xff1a;量子加速超级计算简介(2024年 3月 13日) By Mark Wolf https://developer.nvidia.cn/zh-cn/blog/an-introduction-to-quantum-accelerated-supercomputing/ 文章目录 一、概述二、量子计算机的构建块&#xff1a;QPU 和量子位三、量子计算硬件和算法四、…...

Unity3D 基于YooAssets的资源管理详解

前言 Unity3D 是一款非常流行的游戏开发引擎&#xff0c;它提供了丰富的功能和工具来帮助开发者快速创建高质量的游戏和应用程序。其中&#xff0c;资源管理是游戏开发中非常重要的一部分&#xff0c;它涉及到如何有效地加载、管理和释放游戏中的各种资源&#xff0c;如模型、…...

Linux 自动化升级Jar程序,指定Jar程序版本进行部署脚本

文章目录 一、环境准备二、脚本1. 自动化升级Jar程序2. 指定Jar程序版本进行部署总结一、环境准备 本文在 CentOS 7.9 环境演示,以springboot为例,打包后生成文件名加上版本号,如下打包之后为strategy-api-0.3.2.jar: pom.xml<?xml version="1.0" encoding=&…...

python练习五

Title1&#xff1a;请实现一个装饰器&#xff0c;每次调用函数时&#xff0c;将函数名字以及调用此函数的时间点写入文件中 代码&#xff1a; import time time time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 获取当前的时间戳 # 定义一个有参装饰器来实…...

YOLOv1深入解析与实战:目标检测算法原理

参考&#xff1a; https://zhuanlan.zhihu.com/p/667046384 https://blog.csdn.net/weixin_41424926/article/details/105383064 https://arxiv.org/pdf/1506.02640 1. 算法介绍 学习目标检测算法&#xff0c;yolov1是必看内容&#xff0c;不同于生成模型&#xff0c;没有特别…...

Apache Calcite - 自定义标量函数

前言 上一篇文章中我们介绍了calcite中内置函数的使用。实际需求中会遇到一些场景标准内置函数无法满足需求&#xff0c;这时候就需要用到自定义函数。在 Apache Calcite 中添加自定义函数&#xff0c;以便在 SQL 查询中使用自定义的逻辑。这对于执行特定的数据处理或分析任务…...

STM32作业实现(四)光敏传感器

目录 STM32作业设计 STM32作业实现(一)串口通信 STM32作业实现(二)串口控制led STM32作业实现(三)串口控制有源蜂鸣器 STM32作业实现(四)光敏传感器 STM32作业实现(五)温湿度传感器dht11 STM32作业实现(六)闪存保存数据 STM32作业实现(七)OLED显示数据 STM32作业实现(八)触摸按…...

HTML+CSS 文本动画卡片

效果演示 实现了一个图片叠加文本动画效果的卡片&#xff08;Card&#xff09;布局。当鼠标悬停在卡片上时&#xff0c;卡片上的图片会变为半透明&#xff0c;同时显示隐藏在图片上的文本内容&#xff0c;并且文本内容有一个从左到右的渐显动画效果&#xff0c;伴随着一个白色渐…...

MongoDB CRUD操作: 在本地实例进行文本搜索查询

MongoDB CRUD操作&#xff1a; 在本地实例进行文本搜索查询 文章目录 MongoDB CRUD操作&#xff1a; 在本地实例进行文本搜索查询举例创建集合创建文本索引精准搜索排除短语结果排序 在本地实例运行文本搜索查询前&#xff0c;必须先在集合上建立文本索引。MongoDB提供文本索引…...

文档智能开源软件

文档智能介绍&#xff1a; 文档智能通常指的是利用人工智能技术来处理和分析文档内容&#xff0c;以实现自动化、智能化的文档管理。文档智能的应用领域非常广泛&#xff0c;包括但不限于&#xff1a; 1. **文档识别**&#xff1a;使用OCR&#xff08;光学字符识别&#xff0…...

[C][可变参数列表]详细讲解

目录 1.宏含义及使用2.宏原理分析1.原理2.宏理解 1.宏含义及使用 依赖库stdarg.hva_list 其实就是char*类型&#xff0c;方便后续按照字节进行指针移动 va_start(arg, num) 使arg指向可变参数部分(num后面) va_arg(arg, int) 先让arg指向下个元素&#xff0c;然后使用相对位置…...

54. 螺旋矩阵【rust题解】

题目 给你一个 m 行 n 列的矩阵 matrix &#xff0c;请按照 顺时针螺旋顺序 &#xff0c;返回矩阵中的所有元素。 示例 示例 1 输入&#xff1a;matrix [[1,2,3],[4,5,6],[7,8,9]] 输出&#xff1a;[1,2,3,6,9,8,7,4,5] 示例 2 输入&#xff1a;matrix [[1,2,3,4],[5,6,…...

C++_核心编程_多态案例二-制作饮品

#include <iostream> #include <string> using namespace std;/*制作饮品的大致流程为&#xff1a;煮水 - 冲泡 - 倒入杯中 - 加入辅料 利用多态技术实现本案例&#xff0c;提供抽象制作饮品基类&#xff0c;提供子类制作咖啡和茶叶*//*基类*/ class AbstractDr…...

从WWDC看苹果产品发展的规律

WWDC 是苹果公司一年一度面向全球开发者的盛会&#xff0c;其主题演讲展现了苹果在产品设计、技术路线、用户体验和生态系统构建上的核心理念与演进脉络。我们借助 ChatGPT Deep Research 工具&#xff0c;对过去十年 WWDC 主题演讲内容进行了系统化分析&#xff0c;形成了这份…...

高频面试之3Zookeeper

高频面试之3Zookeeper 文章目录 高频面试之3Zookeeper3.1 常用命令3.2 选举机制3.3 Zookeeper符合法则中哪两个&#xff1f;3.4 Zookeeper脑裂3.5 Zookeeper用来干嘛了 3.1 常用命令 ls、get、create、delete、deleteall3.2 选举机制 半数机制&#xff08;过半机制&#xff0…...

STM32标准库-DMA直接存储器存取

文章目录 一、DMA1.1简介1.2存储器映像1.3DMA框图1.4DMA基本结构1.5DMA请求1.6数据宽度与对齐1.7数据转运DMA1.8ADC扫描模式DMA 二、数据转运DMA2.1接线图2.2代码2.3相关API 一、DMA 1.1简介 DMA&#xff08;Direct Memory Access&#xff09;直接存储器存取 DMA可以提供外设…...

将对透视变换后的图像使用Otsu进行阈值化,来分离黑色和白色像素。这句话中的Otsu是什么意思?

Otsu 是一种自动阈值化方法&#xff0c;用于将图像分割为前景和背景。它通过最小化图像的类内方差或等价地最大化类间方差来选择最佳阈值。这种方法特别适用于图像的二值化处理&#xff0c;能够自动确定一个阈值&#xff0c;将图像中的像素分为黑色和白色两类。 Otsu 方法的原…...

在Ubuntu中设置开机自动运行(sudo)指令的指南

在Ubuntu系统中&#xff0c;有时需要在系统启动时自动执行某些命令&#xff0c;特别是需要 sudo权限的指令。为了实现这一功能&#xff0c;可以使用多种方法&#xff0c;包括编写Systemd服务、配置 rc.local文件或使用 cron任务计划。本文将详细介绍这些方法&#xff0c;并提供…...

大模型多显卡多服务器并行计算方法与实践指南

一、分布式训练概述 大规模语言模型的训练通常需要分布式计算技术,以解决单机资源不足的问题。分布式训练主要分为两种模式: 数据并行:将数据分片到不同设备,每个设备拥有完整的模型副本 模型并行:将模型分割到不同设备,每个设备处理部分模型计算 现代大模型训练通常结合…...

MySQL中【正则表达式】用法

MySQL 中正则表达式通过 REGEXP 或 RLIKE 操作符实现&#xff08;两者等价&#xff09;&#xff0c;用于在 WHERE 子句中进行复杂的字符串模式匹配。以下是核心用法和示例&#xff1a; 一、基础语法 SELECT column_name FROM table_name WHERE column_name REGEXP pattern; …...

根据万维钢·精英日课6的内容,使用AI(2025)可以参考以下方法:

根据万维钢精英日课6的内容&#xff0c;使用AI&#xff08;2025&#xff09;可以参考以下方法&#xff1a; 四个洞见 模型已经比人聪明&#xff1a;以ChatGPT o3为代表的AI非常强大&#xff0c;能运用高级理论解释道理、引用最新学术论文&#xff0c;生成对顶尖科学家都有用的…...

python执行测试用例,allure报乱码且未成功生成报告

allure执行测试用例时显示乱码&#xff1a;‘allure’ &#xfffd;&#xfffd;&#xfffd;&#xfffd;&#xfffd;ڲ&#xfffd;&#xfffd;&#xfffd;&#xfffd;ⲿ&#xfffd;&#xfffd;&#xfffd;Ҳ&#xfffd;&#xfffd;&#xfffd;ǿ&#xfffd;&am…...