Collections集合中方法的使用
发布日期:2021-05-07 11:03:52 浏览次数:15 分类:技术文章

本文共 1482 字,大约阅读时间需要 4 分钟。

1、Collections.reverse方法

对list集合进行降序排序
reverse的意思是反转,而不是降序。只是将list集合原来的顺序反转了一下,反转并不意味着降序了。所以要想实现降序,可以先对集合进行升序,然后再反转,这样就降序了。
代码如下:

import java.util.*;public class Test {     private static Map
map = new HashMap
(); public static void main(String[] args) { long[] data = { 1506326821000l, 1506327060000l, 1506326880000l, 1506327000000l, 1506326940000l, 1506326760000l, 1506326700000l}; List list = new ArrayList<>(); for (long key : data) { list.add(key); } System.out.println(list); //先升序 Collections.sort(list); System.out.println(list); //再反转 Collections.reverse(list); System.out.println(list); }}

输出结果:

[1506326821000, 1506327060000, 1506326880000, 1506327000000, 1506326940000, 1506326760000, 1506326700000][1506326700000, 1506326760000, 1506326821000, 1506326880000, 1506326940000, 1506327000000, 1506327060000][1506327060000, 1506327000000, 1506326940000, 1506326880000, 1506326821000, 1506326760000, 1506326700000]

2、Collections.singleton

返回只包含特定对象的集合
代码如下:

String init[] = {    "One", "Two", "Three", "One", "Two", "Three" };  List list1 = new ArrayList(Arrays.asList(init));  List list2 = new ArrayList(Arrays.asList(init));  list1.remove("One");  System.out.println(list1);   // [Two, Three, One, Two, Three]  list2.removeAll(Collections.singleton("One"));  System.out.println(list2);  // [Two, Three, Two, Three]  userOnlineList.removeAll(Collections.singleton(null));//去除userOnlineList对象中字段值为null的数据
上一篇:Java箭头函数,lambda表达式
下一篇:Java中如何构建树结构

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年03月18日 01时04分20秒