标签语句分析

return userList.stream().filter(user -> {String tagsStr = user.getTags();

使用 Stream API 来过滤 userList 中的用户

解析 tagsStr 并根据标签进行过滤

假设 tagsStr 是一个 JSON 格式的字符串,存储了一个标签集合。你希望过滤出包含所有指定标签的用户。

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;public List<SafetyUser> filterUsersByTags(List<String> tagNameList) {// 查询所有用户QueryWrapper<User> queryWrapper = new QueryWrapper<>();List<User> userList = userMapper.selectList(queryWrapper);// 使用 Gson 解析 JSON 字符串Gson gson = new Gson();Type setType = new TypeToken<Set<String>>() {}.getType();// 过滤用户return userList.stream().filter(user -> {String tagsStr = user.getTags();if (StringUtils.isBlank(tagsStr)) {return false;}Set<String> tempTagNameSet = gson.fromJson(tagsStr, setType);tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());return tagNameList.stream().allMatch(tempTagNameSet::contains);}).map(this::getSafetyUser).collect(Collectors.toList());
}
Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {}.getType());

使用了 Gson 来将一个 JSON 格式的字符串解析为一个 Set<String> 类型

假设 tagsStr 是一个 JSON 格式的字符串,存储了一个标签集合。你希望将这个字符串解析为一个 Set<String>

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.Set;public class Example {public static void main(String[] args) {// 示例 JSON 字符串String tagsStr = "[\"tag1\", \"tag2\", \"tag3\"]";// 创建 Gson 实例Gson gson = new Gson();// 使用 TypeToken 获取 Set<String> 的类型Type setType = new TypeToken<Set<String>>() {}.getType();// 解析 JSON 字符串为 Set<String>Set<String> tempTagNameSet = gson.fromJson(tagsStr, setType);// 输出结果System.out.println(tempTagNameSet);}
}
Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {}.getType());

你的代码片段中使用了 `Gson` 来将一个 JSON 格式的字符串解析为一个 `Set<String>` 类型。

### 完整代码示例

假设 `tagsStr` 是一个 JSON 格式的字符串,存储了一个标签集合。你希望将这个字符串解析为一个 `Set<String>`。

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.Set;public class Example {public static void main(String[] args) {// 示例 JSON 字符串String tagsStr = "[\"tag1\", \"tag2\", \"tag3\"]";// 创建 Gson 实例Gson gson = new Gson();// 使用 TypeToken 获取 Set<String> 的类型Type setType = new TypeToken<Set<String>>() {}.getType();// 解析 JSON 字符串为 Set<String>Set<String> tempTagNameSet = gson.fromJson(tagsStr, setType);// 输出结果System.out.println(tempTagNameSet);}
}

### 代码解释

1. **创建 Gson 实例**:

   Gson gson = new Gson();

   这里创建了一个 `Gson` 实例,用于后续的 JSON 解析。

2. **获取 `Set<String>` 的类型**:

   Type setType = new TypeToken<Set<String>>() {}.getType();

   - `TypeToken` 是一个辅助类,用于获取泛型类型的 `Type`。
   - `new TypeToken<Set<String>>() {}.getType()` 会返回一个 `Type` 对象,表示 `Set<String>` 类型。
   - 这是因为 Java 的泛型在运行时会被擦除,所以需要通过 `TypeToken` 来保留泛型信息。

3. **解析 JSON 字符串**:

   Set<String> tempTagNameSet = gson.fromJson(tagsStr, setType);

   - `gson.fromJson(tagsStr, setType)` 方法将 JSON 字符串 `tagsStr` 解析为 `Set<String>` 类型。
   - `tagsStr` 应该是一个 JSON 数组格式的字符串,例如 `["tag1", "tag2", "tag3"]`。

4. **处理空值或异常**:
   在实际应用中,你可能需要处理 `tagsStr` 为空或格式不正确的情况。可以添加一些额外的检查和异常处理:

 try {if (StringUtils.isBlank(tagsStr)) {tempTagNameSet = new HashSet<>();} else {tempTagNameSet = gson.fromJson(tagsStr, setType);}} catch (Exception e) {// 处理解析异常tempTagNameSet = new HashSet<>();System.err.println("Error parsing tags: " + e.getMessage());}

tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());

这行代码使用了 `Optional` 类来处理可能为 `null` 的 `tempTagNameSet`。`Optional` 是 Java 8 引入的一个类,用于避免显式的 `null` 检查,使代码更加简洁和安全。

### 代码解释

- **`Optional.ofNullable(tempTagNameSet)`**:
  - 创建一个 `Optional` 对象,如果 `tempTagNameSet` 为 `null`,则返回一个空的 `Optional`;否则,返回一个包含 `tempTagNameSet` 的 `Optional`。

- **`.orElse(new HashSet<>())`**:
  - 如果 `Optional` 是空的(即 `tempTagNameSet` 为 `null`),则返回一个新的空 `HashSet`;否则,返回 `tempTagNameSet`。

### 作用

这行代码的作用是确保 `tempTagNameSet` 不会为 `null`。如果 `tempTagNameSet` 为 `null`,则用一个空的 `HashSet` 替代,避免后续代码中出现 `NullPointerException`。

### 示例

假设你从 JSON 字符串解析出的 `Set<String>` 可能为 `null`,你希望确保它不会为 `null`:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.*;public class Example {public static void main(String[] args) {// 示例 JSON 字符串String tagsStr = "[\"tag1\", \"tag2\", \"tag3\"]";// 创建 Gson 实例Gson gson = new Gson();// 使用 TypeToken 获取 Set<String> 的类型Type setType = new TypeToken<Set<String>>() {}.getType();// 解析 JSON 字符串为 Set<String>Set<String> tempTagNameSet = null; // 假设解析失败,tempTagNameSet 为 nulltry {tempTagNameSet = gson.fromJson(tagsStr, setType);} catch (Exception e) {e.printStackTrace();}// 确保 tempTagNameSet 不为 nulltempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());// 输出结果System.out.println(tempTagNameSet);}
}

### 优化和注意事项

1. **异常处理**:
   在实际应用中,应该处理可能的异常,例如 JSON 格式错误或解析失败。


   try {
       tempTagNameSet = gson.fromJson(tagsStr, setType);
   } catch (Exception e) {
       log.error("Error parsing tags: {}", tagsStr, e);
       tempTagNameSet = new HashSet<>();
   }
 

2. **空值处理**:
   如果 `tagsStr` 为空或 `null`,应该提供一个默认值。


   if (StringUtils.isBlank(tagsStr)) {
       tempTagNameSet = new HashSet<>();
   } else {
       try {
           tempTagNameSet = gson.fromJson(tagsStr, setType);
       } catch (Exception e) {
           log.error("Error parsing tags: {}", tagsStr, e);
           tempTagNameSet = new HashSet<>();
       }
   }
 

3. **性能优化**:
   如果你需要频繁解析类似的 JSON 字符串,可以考虑缓存 `Gson` 实例,避免每次创建新的实例。

### 完整的过滤方法

结合你的需求,以下是一个完整的过滤方法示例:


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;public List<SafetyUser> filterUsersByTags(List<String> tagNameList) {// 查询所有用户QueryWrapper<User> queryWrapper = new QueryWrapper<>();List<User> userList = userMapper.selectList(queryWrapper);// 使用 Gson 解析 JSON 字符串Gson gson = new Gson();Type setType = new TypeToken<Set<String>>() {}.getType();// 过滤用户return userList.stream().filter(user -> {String tagsStr = user.getTags();Set<String> tempTagNameSet = new HashSet<>();try {if (StringUtils.isNotBlank(tagsStr)) {tempTagNameSet = gson.fromJson(tagsStr, setType);}} catch (Exception e) {log.error("Error parsing tags for user {}: {}", user.getId(), tagsStr, e);}tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());return tagNameList.stream().allMatch(tempTagNameSet::contains);}).map(this::getSafetyUser).collect(Collectors.toList());
}

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/78757.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【应用密码学】实验四 公钥密码1——数学基础

一、实验要求与目的 学习快速模幂运算、扩展欧几里得、中国剩余定理的算法思想以及代码实现。 二、实验内容与步骤记录&#xff08;只记录关键步骤与结果&#xff0c;可截图&#xff0c;但注意排版与图片大小&#xff09; 1.快速模幂运算的设计思路 快速模幂运算的核心思想…

WebSocket与Socket、TCP、HTTP的关系及区别

1.什么是WebSocket及原理 WebSocket是HTML5中新协议、新API。 WebSocket从满足基于Web的日益增长的实时通信需求应运而生&#xff0c;解决了客户端发起多个Http请求到服务器资源浏览器必须要在经过长时间的轮询问题&#xff0c;实现里多路复用&#xff0c;是全双工、双向、单套…

基于C++的IOT网关和平台4:github项目ctGateway交互协议

初级代码游戏的专栏介绍与文章目录-CSDN博客 我的github:codetoys,所有代码都将会位于ctfc库中。已经放入库中我会指出在库中的位置。 这些代码大部分以Linux为目标但部分代码是纯C++的,可以在任何平台上使用。 源码指引:github源码指引_初级代码游戏的博客-CSDN博客 系…

【PPT制作利器】DeepSeek + Kimi生成一个初始的PPT文件

如何基于DeepSeek Kimi进行PPT制作 步骤&#xff1a; Step1&#xff1a;基于DeepSeek生成文本&#xff0c;提问 Step2基于生成的文本&#xff0c;用Kimi中PPT助手一键生成PPT 进行PPT渲染-自动渲染 可选择更改模版 生成PPT在桌面 介绍的比较详细&#xff0c;就是这个PPT模版…

拷贝多个Excel单元格区域为图片并粘贴到Word

Excel工作表Sheet1中有两个报表&#xff0c;相应单元格区域分别定义名称为Report1和Report2&#xff0c;如下图所示。 现在需要将图片拷贝图片粘贴到新建的Word文档中。 示例代码如下。 Sub Demo()Dim oWordApp As ObjectDim ws As Worksheet: Set ws ThisWorkbook.Sheets(&…

Spring是如何传播事务的?什么是事务传播行为

Spring是如何传播事务的&#xff1f; Spring框架通过声明式事务管理来传播事务&#xff0c;主要依赖于AOP&#xff08;面向切面编程&#xff09;和事务拦截器来实现。Spring的事务传播机制是基于Java Transaction API (JTA) 或者本地资源管理器&#xff08;如Hibernate、JDBC等…

Python-pandas-操作Excel文件(读取数据/写入数据)及Excel表格列名操作详细分享

Python-pandas-操作Excel文件(读取数据/写入数据) 提示&#xff1a;帮帮志会陆续更新非常多的IT技术知识&#xff0c;希望分享的内容对您有用。本章分享的是pandas的使用语法。前后每一小节的内容是存在的有&#xff1a;学习and理解的关联性。【帮帮志系列文章】&#xff1a;每…

PHP分页显示数据,在phpMyadmin中添加数据

<?php $conmysqli_connect(localhost,root,,stu); mysqli_query($con,"set names utf8"); //设置字符集为utf8 $sql"select * from teacher"; $resultmysqli_query($con,$sql); $countmysqli_num_rows($result); //记录总条数$count。 $pagesize10;//每…

智能参谋部系统架构和业务场景功能实现

将以一个基于微服务和云原生理念、深度集成人工智能组件、强调实时性与韧性的系统架构为基础,详细阐述如何落地“智能参谋部”的各项能力。这不是一个简单的软件堆叠,而是一个有机整合了数据、知识、模型、流程与人员的复杂体系。 系统愿景:“智能参谋部”——基于AI赋能的…

企业级RAG架构设计:从FAISS索引到HyDE优化的全链路拆解,金融/医疗领域RAG落地案例与避坑指南(附架构图)

本文较长&#xff0c;纯干货&#xff0c;建议点赞收藏&#xff0c;以免遗失。更多AI大模型应用开发学习内容&#xff0c;尽在聚客AI学院。 一. RAG技术概述 1.1 什么是RAG&#xff1f; RAG&#xff08;Retrieval-Augmented Generation&#xff0c;检索增强生成&#xff09; 是…

Spring Boot Validation实战详解:从入门到自定义规则

目录 一、Spring Boot Validation简介 1.1 什么是spring-boot-starter-validation&#xff1f; 1.2 核心优势 二、快速集成与配置 2.1 添加依赖 2.2 基础配置 三、核心注解详解 3.1 常用校验注解 3.2 嵌套对象校验 四、实战开发步骤 4.1 DTO类定义校验规则 4.2 Cont…

理清缓存穿透、缓存击穿、缓存雪崩、缓存不一致的本质与解决方案

在构建高性能系统中&#xff0c;缓存&#xff08;如Redis&#xff09; 是不可或缺的关键组件&#xff0c;它大幅减轻了数据库压力、加快了响应速度。然而&#xff0c;在高并发环境下&#xff0c;缓存也可能带来一系列棘手的问题&#xff0c;如&#xff1a;缓存穿透、缓存击穿、…

PyTorch_构建线性回归

使用 PyTorch 的 API 来手动构建一个线性回归的假设函数&#xff0c;数据加载器&#xff0c;损失函数&#xff0c;优化方法&#xff0c;绘制训练过程中的损失变化。 数据构建 import torch from sklearn.datasets import make_regression import matplotlib.pyplot as plt i…

005-nlohmann/json 基础方法-C++开源库108杰

《二、基础方法》&#xff1a;节点访问、值获取、显式 vs 隐式、异常处理、迭代器、类型检测、异常处理……一节课搞定C处理JSON数据85%的需求…… JSON 字段的简单类型包括&#xff1a;number、boolean、string 和 null&#xff08;即空值&#xff09;&#xff1b;复杂类型则有…

HarmonyOS 5.0 分布式数据协同与跨设备同步​​

大家好&#xff0c;我是 V 哥。 使用 Mate 70有一段时间了&#xff0c;系统的丝滑使用起来那是爽得不要不要的&#xff0c;随着越来越多的应用适配&#xff0c;目前使用起来已经和4.3的兼容版本功能差异无碍了&#xff0c;还有些纯血鸿蒙独特的能力很是好用&#xff0c;比如&am…

Linux云计算训练营笔记day02(Linux、计算机网络、进制)

Linux 是一个操作系统 Linux版本 RedHat Rocky Linux CentOS7 Linux Ubuntu Linux Debian Linux Deepin Linux 登录用户 管理员 root a 普通用户 nsd a 打开终端 放大: ctrl shift 缩小: ctrl - 命令行提示符 [rootlocalhost ~]# ~ 家目录 /root 当前登录的用户…

macOS 安装了Docker Desktop版终端docker 命令没办法使用

macOS 安装了Docker Desktop版终端docker 命令没办法使用 1、检查Docker Desktop能否正常运行。 确保Docker Desktop能正常运行。 2、检查环境变量是否添加 1、添加环境变量 如果环境变量中没有包含Docker的路径&#xff0c;你可以手动添加。首先&#xff0c;找到Docker的…

Gradio全解20——Streaming:流式传输的多媒体应用(5)——基于WebRTC的摄像头实时目标检测

Gradio全解20——Streaming&#xff1a;流式传输的多媒体应用&#xff08;5&#xff09;——基于WebRTC的摄像头实时目标检测 本篇摘要20. Streaming&#xff1a;流式传输的多媒体应用20.5 基于WebRTC的摄像头实时目标检测20.5.1 环境配置及说明1. WebRTC2. TURN服务器 20.5.2 …

OSCP - Proving Grounds - NoName

主要知识点 linux命令注入SUID find提权 具体步骤 从nmap开始搜集信息&#xff0c;只开放了一个80端口 Nmap scan report for 192.168.171.15 Host is up (0.40s latency). Not shown: 65534 closed tcp ports (reset) PORT STATE SERVICE VERSION 80/tcp open http …

c++_csp-j算法 (6)_高精度算法(加减乘除)

高精度算法 C++高精度算法是指在C++编程语言中实现高精度计算的算法。在C++中,通常整数的范围是有限的,超出这个范围的整数计算会导致溢出。高精度算法的出现,使得C++程序能够处理超出常规整数范围的大整数计算,包括高精度加法、减法、乘法、除法等运算。 在C++中实现高精…