List 去重方法,用stream()将 List< User> 转List< String>
1、LinkedHashSet
LinkedHashSet是ArrayList删除重复优秀方法
1、删除重复数据 2、保持添加到其中的数据的顺序
public class ArrayListDistinct {public static void main(String[] args) {ArrayList<Integer> intList = new ArrayList<>(Arrays.asList(11, 22, 11, 22, 22, 63, 63, 65, 66, 77, 77, 99, 100));System.out.println(intList );LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(intList );ArrayList<Integer> listDistinct = new ArrayList<>(hashSet);System.out.println(listDistinct );}
}
2.使用stream进行去重
java 8 新特性 需要重写 eq 、hashcode方法
ArrayList<Integer> intList = new ArrayList<>(Arrays.asList(11, 22, 11, 22, 22, 63, 63, 65, 66, 77, 77, 99, 100));
List<Integer> listDistinct= intList.stream().distinct().collect(Collectors.toList());System.out.println(listDistinct);
根据多条件 , 判断List重复个数
long count = addList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(po -> DateTimeFormatter.ofPattern("yyyy-MM-dd").format(po.getOrderTime()) + ";" + po.getCityCode()))), ArrayList::new)).stream().count();
3.利用List的contains方法循环遍历
List<String> listDistinct= new ArrayList<String>(intList .size());for (String str : intList ) {if (!listDistinct.contains(str)) {listDistinct.add(str);}}
4.双重for循环去重
for (int i = 0; i < intList .size(); i++) { for (int j = 0; j < intList .size(); j++) { if(i!=j&&intList .get(i)==intList .get(j)) { intList .remove(intList .get(j)); }
}
5.用stream()将 List< User> 转List< String>
List<String> nameList =
list.stream().map(User::getCarUserName).collect(Collectors.toList());
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
