日拱一卒:Java 集合类型转换

2023-09-25  本文已影响0人  Tinyspot

1. Convert List to Array

@Test
public void demo() {
    UserDTO userDTO = new UserDTO("Tinyspot", 20);
    // 注意:若包装类未赋值,直接做判断会 java.lang.NullPointerException
    // if (userDTO.getStatus() == 0) {}

    List<Object> list = Arrays.asList(userDTO, "1001");
    // [UserDTO(name=Tinyspot, age=20, status=null, total=null), 1001]
    System.out.println(list);
    /*
    * List.toArray() --> Object[]
    * [{"age":20,"name":"Tinyspot"},"1001"]
    */
    System.out.println(JSON.toJSONString(list.toArray()));
}

2. Convert List to Set

@Test
public void listToSet() {
    List<String> ids = Lists.newArrayList("111", "222", "111");

    // Pattern one: With Plain Java
    Set<String> idSet = new HashSet<>(ids);

    // Pattern two: With Guava
    Set<String> idSet2 = Sets.newHashSet(ids);
}

2.1 addAll()

@Test
public void setAddAll() {
    Set<String> targetSet = Sets.newHashSet("101");
    List<String> sourceList = Lists.newArrayList("111", "222", "111");

    // Set.addAll(Collection<? extends E> c)
    targetSet.addAll(sourceList);

    // or: With Apache Commons Collections
    // CollectionUtils.addAll(targetSet, sourceList);
    System.out.println(targetSet);
}

3. Convert Set to List

@Test
public void setToList() {
    Set<String> idSet = Sets.newHashSet("101");

    // Pattern one: With Plain Java
    List<String> ids = new ArrayList<>(idSet);

    // Pattern two: With Guava
    List<String> ids2 = Lists.newArrayList(idSet);
}

3.1 addAll()

@Test
public void listAddAll() {
    List<String> ids = Lists.newArrayList("111", "222", "111");
    Set<String> idSet = Sets.newHashSet("101");

    // List.addAll(Collection<? extends E> c)
    ids.addAll(idSet);

    /*
    * or: With Apache Commons Collections
    *   CollectionUtils.addAll(Collection, Iterable)
    *       Adds all elements in the Iterable to the given collection
    */
    // CollectionUtils.addAll(ids, idSet);
    System.out.println(ids);
}

4. Map

@Test
public void mapKeySetToList() {
    List<String> ids = Lists.newArrayList("111");

    Map<String, String> map = new HashMap<>();
    map.put("101", "000");

    // Map.keySet() --> Set<K>
    ids.addAll(map.keySet());
    System.out.println(ids);
}
上一篇下一篇

猜你喜欢

热点阅读