java集合之间的相互转换

将Map集合的键key转换成set集合
Map hashMap = new HashMap<>();
hashMap.put(“夔牛”, “重庆”);
hashMap.put(“神盾”, “深圳”);
将map 键key成set
Set mapKeySet = hashMap.keySet();
System.out.println(mapKeySet);
将map 值value转化成set
Set mapValueSet = new HashSet<>(hashMap.values());
System.out.println(mapValueSet);
将map 键key转化成List
List mapKeyList = new ArrayList<>();
System.out.println(hashMap.keySet());
将map 值value转化成list
List mapValueList = new ArrayList<>();
System.out.println(hashMap.values());
将数组转化成set
String[] arr = {“重慶”, “成都”, “四川”};
Set hashSet = new HashSet<>(Arrays.asList(arr));
System.out.println(hashSet);
set转化成数组
Set set = new HashSet<>();
set.add(“江北”);
set.add(“渝北”);
String[] arrs = new String[set.size()];
set.toArray(arrs);
System.out.println(Arrays.toString(arrs));
list转化成set
List list = new ArrayList<>();
list.add(100);
list.add(200);
Set listSet = new HashSet<>(list);
System.out.println(“list转化成set:”+listSet);
set转化成list
Set setList = new HashSet<>();
setList.add(300);
setList.add(400);
List setsList = new ArrayList<>(setList);
System.out.println(“set转化成list”+setList);
list转化成数组
List arrayList = new ArrayList<>();
arrayList.add(500);
arrayList.add(600);
Integer[] s = new Integer[arrayList.size()];
arrayList.toArray(s);
System.out.println(Arrays.toString(s));
数组转化成list
String[] shuzu = {“美国”, “日本”};
List list1 = Arrays.asList(shuzu);
List list2 = Arrays.asList(“aaa”, “ccc”);
System.out.println(list1);
System.out.println(list2);
List转Map的方法
public void test3(){
List userList = new ArrayList<>();
User user1 = new User();
user1.setId(1L);
user1.setName(“刘备”);
User user2 = new User();
user2.setId(2L);
user2.setName(“关羽”);
userList.add(user1);
userList.add(user2);
HashMap map = new HashMap<>();
for循环list转换map
for (User user : userList) {
map.put(user.getId(), user);
}
System.out.println(“list转map”+map);
使用JDK1.8 list转换map
Map maps = userList.stream().collect(Collectors.toMap(User::getId, user -> user));
System.out.println(maps);
}
public static class User{
private Long id;
private String name;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

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

你可能感兴趣的:(java技术,java集合之间的相互转换)