List的五种去重方式

一、String去重:

//set集合去重,不改变原有的顺序public static void pastLeep1(List<String> list){System.out.println("list = [" + list.toString() + "]");List<String> listNew=new ArrayList<>();Set set=new HashSet();for (String str:list) {if(set.add(str)){listNew.add(str);}}System.out.println("listNew = [" + listNew.toString() + "]");}//遍历后判断赋给另一个list集合public static void pastLeep2(List<String> list){System.out.println("list = [" + list.toString() + "]");List<String> listNew=new ArrayList<>();for (String str:list) {if(!listNew.contains(str)){listNew.add(str);}}System.out.println("listNew = [" + listNew.toString() + "]");}//set去重public static void pastLeep3(List<String> list){System.out.println("list = [" + list + "]");Set set = new HashSet();List<String> listNew=new ArrayList<>();set.addAll(list);listNew.addAll(set);System.out.println("listNew = [" + listNew + "]");}//set去重(缩减为一行)public static void pastLeep4(List<String> list){System.out.println("list = [" + list + "]");List<String> listNew=new ArrayList<>(new HashSet(list));System.out.println("listNew = [" + listNew + "]");}//去重并按自然顺序排序public static void pastLeep5(List<String> list){System.out.println("list = [" + list + "]");List<String> listNew=new ArrayList<>(new TreeSet<String>(list));System.out.println("listNew = [" + listNew + "]");}


二、对象去重方法:
package com.hcycom.iams.ncolog;

import java.util.*;
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

public class Test {

public static void main(String[] args) {
Data data1 = new Data(1,"aaaa");
Data data2 = new Data(2,"dddd");
Data data3 = new Data(1,"vvvv");
Data data4 = new Data(4,"rrrr");
Data data5 = new Data(1,"ssss");
List<Data> list = Arrays.asList(data1,data2,data3,data4,data5);
List<Data> l = test2(list);
System.out.println(Arrays.toString(l.toArray()));

}

//对象去重
public static List<Data> test2(List<Data> list){
List<Data> unique = list.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(Data::getId))), ArrayList::new)
);
return unique;
}
}

// 实体对象
class Data{

private int id;
private String name;

public Data(int id, String name) {
this.id = id;
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Data{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

转载于:https://www.cnblogs.com/typ1805/p/8068289.html

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

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

相关文章

python Shapely OSError: Could not find lib c or load any of its variants []

mac 升级过后&#xff0c;python项目运行报错python Shapely OSError: Could not find lib c or load any of its variants []。 在github上找到解决办法没记录如下&#xff1a; To recap, I removed anything dealing with conda that depends on geos: conda remove geos, s…

工作192:vue项目如何刷新当前页面

1.场景 在处理列表时&#xff0c;常常有删除一条数据或者新增数据之后需要重新刷新当前页面的需求。 2.遇到的问题 1. 用vue-router重新路由到当前页面&#xff0c;页面是不进行刷新的 2.采用window.reload()&#xff0c;或者router.go(0)刷新时&#xff0c;整个浏览器进行…

python保存文件,如果目录不存在,则创建

对于python 3.2 以上版本使用 import osfilename "/user/project/demo.txt" os.makedirs(os.path.dirname(filename), exist_okTrue) with open(filename, "w") as f:f.write("FOOBAR")

CentOS挂Windows的NFS备忘

Windows NFS 安装和配置 注&#xff1a;需要将名称为“所有计算机”的访问类型改为“无访问权限”&#xff0c;再将可访问IP的访问类型改为“读写”&#xff0c;并勾选“允许根目录访问” &#xff0c;如WINDOWS有防火墙开放“2049”端口 CentOS需要开启两个服务&#xff1a; y…

NotificationManager: notifyAsUser: tag=null, id=6, user=UserHandle{0}

Android studio 使用 targetSdkVersion 28 在Android系统大于等于8.0的时候&#xff0c;通知不显示bug解决方法&#xff1a; 1、修改appcompat版本&#xff0c;如果是小于v27 改为 implementation com.android.support:appcompat-v7:27.1.1 2、添加依赖 compile com.git…

工作193:vue.runtime.esm.js?2b0e:619 [Vue warn]: <transition-group> children must be keyed: <ElTag>

标题[Vue warn]: children must be keyed: 今天学习了VUE的列表排序过渡 碰见报错 报错之前代码为&#xff1a; <transition-group name"flip-list" tag"div"><van-cell v-for"(item,i) in list" v-bind:key"item.id">{…

prettier 配置参数说明

有必要使用prettier进行代码格式化。 1、常用的配置说明如下&#xff1a; {// 使能每一种语言默认格式化规则"[html]": {"editor.defaultFormatter": "esbenp.prettier-vscode"},"[css]": {"editor.defaultFormatter": &qu…

Oracle之例外(异常)

/* 例外 其实就是异常 处理发生的异常 java try{}catch(OutofBoundIndexException){}catch(Exception e){} 数据库对异常的处理 exception when 异常类型 then 处理语句 数据库异常分类 运行时异常 编…

Android2.2查看svn历史提交记录

一开始时是没有显示历史提交记录的&#xff0c;方法很简单 VCS--Subversion--ShowHistory,之后在下面的Version control就会显示“History-项目名”这个栏目&#xff0c;在这个栏目下面就可以查看提交的历史记录了 方法2&#xff1a; 对文件夹点右键&#xff0c;点击TortoiseS…

工作194:vue.runtime.esm.js?2b0e:619 [Vue warn]: Duplicate keys detected: ‘/system‘. This may cause an

错误如下 拿到公司一个小哥哥的代码&#xff0c;一来就报了一堆bug&#xff0c;吓得我先写一篇博客vue.runtime.esm.js?2b0e:619 [Vue warn]: Duplicate keys detected: /system. This may cause an update error.found in---> <Sidebar> at src/layout/components/S…

STM32 RS485 和串口 只能接收不能发送问题解决

串口 发送引脚要配置输出频率 否则配置不成功&#xff0c;导致只能接受不能发送转载于:https://www.cnblogs.com/yekongdexingxing/p/8078936.html

echarts我常用的参数总结

1、 progressive 表示ECharts渐进式渲染时每一帧绘制图形数量&#xff0c;设为 0 时不启用渐进式渲染&#xff0c;支持每个系列单独配置。 在图中有数千图形甚至好几万图形的时候&#xff0c;一下子把图形绘制出来&#xff0c;或者交互重绘的时候可能会造成界面的卡顿甚至假死…

Android 折叠头部监听,抽屉式动画

实现方法2&#xff1a;https://blog.csdn.net/meixi_android/article/details/84136375 1、自定义scrollview,监听上下滑动距离&#xff1a; public class ScrollListenerView extends ScrollView {private ScrollListener scrollViewListener null;public ScrollListenerVie…

工作195:解决key值不唯一的报错

<!--投放权限--><!--获取投放权限的数据--><el-form-item label"投放权限" :label-width"formLabelWidth"><el-selectv-model"form.publish_permission"multipleplaceholder"请选择投放权限"><el-option v…

POJ1459 Power Network —— 最大流

题目链接&#xff1a;https://vjudge.net/problem/POJ-1459 Power NetworkTime Limit: 2000MS Memory Limit: 32768KTotal Submissions: 29270 Accepted: 15191Description A power network consists of nodes (power stations, consumers and dispatchers) connected by power…

Python 异步操作文件 aiofiles

# 异步文件操作 # pip install aiofiles# 基本用法 import asyncio import aiofilesasync def wirte_demo():# 异步方式执行with操作,修改为 async withasync with aiofiles.open("text.txt","w",encoding"utf-8") as fp:await fp.write("h…

工作196:注意接收数据的格式

<!--获取投放权限的数据--><el-form-item label"投放权限" :label-width"formLabelWidth"><el-selectv-model"form.publish_permission"multipleplaceholder"请选择投放权限"><el-option v-for"(publish,in…

uvicorn 更改fastapi 运行host和port

在命令行输入uvicorn --help可以显示参数介绍&#xff0c;主要两个参数: --host TEXT Bind socket to this host. [default:127.0.0.1] --port INTEGER Bind socket to this port. [default: 8000]所以运行命令可以改成&#xff1a; uvicorn …

mysql问题处理积累

1.mysql errors:message from server: "Host xxx is blocked because of many connection errors; unblock 数据库连接抛了异常&#xff1a;null, message from server: "Host PC-20130201IBXI is blocked because of many connection errors; unblock with mysqlad…