在java中,我们经常需要对List、Array等做一些转换操作,当然转换方法有很多种,但哪种方法既方便又高效呢?在这里向大家介绍一下集合间的最佳转换方法。
方法/步骤
1List转换为ArrayList list = new ArrayList<>();list.add('AAAA');list.add('BBBB');list.add('CCCC');list.add('DDDD');String [] array = list.toArray(new String[list.size()]);
2Array转换为ListString[] countries = {'AAAA', 'BBBB', 'CCCC', 'DDDD'};List list = Arrays.asList(countries);
3Map的Key值转换为ListMap map = new HashMap<>();map.put(1,'AAAA');map.put(2,'BBBB');map.put(3,'CCCC');map.put(4,'DDDD');List list = new ArrayList(map.keySet());
4Map的Value值转换为ListMap map = new HashMap<>();map.put(1,'AAAA');map.put(2,'BBBB');map.put(3,'CCCC');map.put(4,'DDDD');List list = new ArrayList(map.values());
6Map的Key值转换为SetMap map = new HashMap<>();map.put(1,'AAAA');map.put(2,'BBBB');map.put(3,'CCCC');map.put(4,'DDDD');Set set = new HashSet<>(map.keySet());
7Map的Value值转换为SetMap map = new HashMap<>();map.put(1,'AAAA');map.put(2,'BBBB');map.put(3,'CCCC');map.put(4,'DDDD');Set set = new HashSet(map.values());