Java集合学习

一、集合的分类:

二、常用的集合:

1、Java collection:Jdk中的集合

1、List

//List
List<String>  list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
System.out.println(list); // [a, b, c]

2、Map

//Map
Map<String,String>  map = new HashMap<>();
map.put("name","by");
map.put("age","18");
System.out.println(map); // {name=by, age=18}

3、Set

//Set
Set<String> set = new HashSet<>();
set.add("a");
set.add("b");
System.out.println(set); // [a, b]

4、Iterator遍历集合

//Iterator遍历List集合
Iterator iterator = list.iterator();
while (iterator.hasNext()){
    String parm = (String) iterator.next();
    System.out.println(parm);
    if(parm.equals("a")){
        iterator.remove();
    }
}
System.out.println(list); // [b, c]

5、遍历MAP

/**
     * 遍历Map
     *
     * 获取方法:
     * 第一种方式: 使用keySet
     * 需要分别获取key和value,没有面向对象的思想
     * Set<K> keySet() 返回所有的key对象的Set集合
     */
   static void traverseMap(){
       Map<Integer, String> map = new HashMap<>();
       map.put(1, "aaaa");
       map.put(2, "bbbb");
       map.put(3, "cccc");
       System.out.println(map);

       Set<Integer> ks = map.keySet();
       Iterator<Integer> it = ks.iterator();
       while (it.hasNext()) {
           Integer key = it.next();
           String value = map.get(key);
           System.out.println("key=" + key + " value=" + value);
       }
   }

2、Guava Collections(google开源工具 )

1、List

//创建List
List<String> list = Lists.newArrayList("a","b","c");
list.add("d");
//反转List
System.out.println(Lists.reverse(list)); // [d, c, b, a]

//将List集合转换为特定规则的字符串
String listResult = Joiner.on("-").join(list);
System.out.println(listResult); // a-b-c-d

2、Map

//定义Map
Map<String,String > map = Maps.newHashMap();
map.put("name","by");
map.put("age","23");
System.out.println(map); //{name=by, age=23}
//将Map集合转换为特定规则的字符串
String mapResult = Joiner.on(",").withKeyValueSeparator("=").join(map);
System.out.println(mapResult); // name=by,age=23

//定义Map中放List的形式(Map<String,List<Integer>>)
Multimap<String,Integer> maps = ArrayListMultimap.create();
maps.put("map",1);
maps.put("map",2);
System.out.println(maps); //{map=[1, 2]}

3、Set

//定义Set
Set<String> set = Sets.newHashSet();
set.add("value");

3、Trove

1、构造基本类型的集合

//直接构造int类型的集合
TIntArrayList intList = new TIntArrayList();
intList.add(1);
intList.add(2);
intList.add(3);
intList.reverse();
System.out.println(intList);

猜你喜欢

转载自www.cnblogs.com/aibaiyang/p/9093730.html