Java中数组、List、Set互相转换

左手的ㄟ右手 2022-05-26 03:55 283阅读 0赞

数组转List

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. List staffsList = Arrays.asList(staffs);

数组转Set

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
  4. staffsSet.add("Mary"); // ok
  5. staffsSet.remove("Tom"); // ok

List转数组

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. List staffsList = Arrays.asList(staffs);
  4. Object[] result = staffsList.toArray();

List转Set

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. List staffsList = Arrays.asList(staffs);
  4. Set result = new HashSet(staffsList);

Set转数组

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
  4. Object[] result = staffsSet.toArray();

Set转List

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
  4. List<String> result = new ArrayList<>(staffsSet);

发表评论

表情:
评论列表 (有 0 条评论,283人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java集合与数组互相转换

    集合与数组互相转换在日常业务开发中必不可少,有时业务需要的是集合,而程序提供的是数组;或者业务需要的是数组,而程序提供的是集合,这就需要转换了。 > 以下简单提供几种常用的