Java中将数组Array转换为列表List的多种实现方式

x33g5p2x  于2022-09-23 转载在 Java  
字(9.1k)|赞(0)|评价(0)|浏览(1107)

本文中将介绍如何使用 Java 将数组转换为列表。我们可以通过多种方式实现它,例如使用 List.ofStream.collectCollections.addAllArrays.asList 方法。 List.ofArrays.asList 返回不可变的 List。我们可以使用不可变的 List 创建 ArrayList 以使其可变。 List 可以使用 List.toArray() 转换回数组。在本文中,我们将实现数组转换为字符串、整数和自定义数据类型的列表。

1. Java 9:使用 List.of

1.List.of 是在 Java 9 中引入的。它返回一个不可变的 List。我们将数组传递给 List.of 方法,它返回一个大小相同的不可变 List

String[] persons = {"Mukesh", "Vishal", "Amar"};
List&ltString> personList = List.of(persons);

2. 在上面的代码片段中,实例 personList 是不可变的。如果我们在其中添加任何元素,如下所示

personList.add("Mohit");

它将抛出以下异常。

Exception in thread "main" java.lang.UnsupportedOperationException

3. 要获得可变列表,我们可以使用 ArrayList,如下所示。

List&ltString> personList = new ArrayList<>(List.of(persons));

现在我们可以在其中添加新元素。
4. 我们可以使用 List 实例中的 toArray() 将列表转换回数组,如下所示。

Object[] persons = personList.toArray();

toArray() 以正确的顺序返回包含该列表中所有元素的数组,即从第一个到最后一个。

查找使用 List.of 将数组转换为列表的示例。
ListOf.java

package com.concretepage;
import java.util.ArrayList;
import java.util.List;
public class ListOf {
  public static void main(String[] args) {
	 System.out.println("---Example-1---");
         String[] persons = {"Mukesh", "Vishal", "Amar"};
	 List&ltString> personList = List.of(persons);
	 personList.forEach(p-> System.out.print(p + " "));		
     
	 System.out.println("\n---Example-2---");
	 personList = new ArrayList<>(List.of(persons));
	 personList.add("Mohit");
	 personList.forEach(p-> System.out.print(p + " "));
	 
	 System.out.println("\n---Example-3---");
	 Book[] books = Book.getBooks();
	 List&ltBook> bookList = List.of(books);
	 bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | "));

	 System.out.println("\n---Example-4---");
	 bookList = new ArrayList<>(List.of(books));
	 bookList.add(new Book("Learning Angular", 250));
	 bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | ")); 
  }
}

输出

---Example-1---
Mukesh Vishal Amar 
---Example-2---
Mukesh Vishal Amar Mohit 
---Example-3---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | 
---Example-4---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | Learning Angular-250 |

Book.java

package com.concretepage;
public class Book {
    private String name;
    private int price;
    public Book(String name, int price) {
	  this.name = name;
	  this.price = price;
    }
    public String getName() {
	  return name;
    }
    public int getPrice() {
	  return price;
    }
    @Override
    public boolean equals(final Object obj) {
      if (obj == null) {
         return false;
      }
      final Book book = (Book) obj;
      if (this == book) {
         return true;
      } else {
         return (this.name.equals(book.name) && this.price == book.price);
      }
    }
    @Override
    public int hashCode() {
      int hashno = 7;
      hashno = 13 * hashno + (name == null ? 0 : name.hashCode());
      return hashno;
    }
    public static Book[] getBooks() {
      Book book1 = new Book("Core Java", 200);
      Book book2 = new Book("Learning Freemarker", 150);        	
      Book book3 = new Book("Spring MVC", 300);
      Book[] books = {book1, book2, book3};
      return books;
    }
}

2. Java 8:使用 Stream.collect

StreamJava 8 中引入。我们可以借助 Collectors.toListCollectors.toCollection 方法使用 Stream.collect 将数组转换为列表。 Stream.collect 使用 Collector 对该流的元素执行可变归约操作。

2.1 Collectors.toList 和 Stream.collect

CollectorsStream 是在 Java 8 中引入的。我们将使用 Collectors.toListStream.collect 方法将数组转换为列表。 Collectors.toList 返回一个 Collector,它将输入元素累积到一个新的 List 中。 Stream.collect 使用 Collector 对此流的元素执行可变归约操作。现在找到使用 Collectors.toListStream.collect 将数组转换为列表的示例。
CollectorsToList.java

package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectorsToList {
  public static void main(String[] args) {
      System.out.println("---Example-1---");		
      String[] persons = {"Mukesh", "Vishal", "Amar"};
      List&ltString> personList = Arrays.stream(persons).collect(Collectors.&ltString&gttoList());
      personList.add("Mohit");
      personList.forEach(p-> System.out.print(p + " "));	

      System.out.println("\n---Example-2---");
      Book[] books = Book.getBooks();
      List&ltBook> bookList = Arrays.stream(books).collect(Collectors.&ltBook&gttoList());
      bookList.add(new Book("Learning Angular", 250));
      bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | ")); 		
  }
}

输出

---Example-1---
Mukesh Vishal Amar Mohit 
---Example-2---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | Learning Angular-250 |

2.2 Collectors.toCollection 与 Stream.collect

我们将使用 Collectors.toCollectionStream.collect 方法将数组转换为列表。 CollectorsStream 是在 Java 8 中引入的。 Collectors.toCollection 返回一个 Collector,它将输入元素按照遇到的顺序累积到一个新的 Collection 中。 Stream.collect 使用 Collector 对此流的元素执行可变归约操作。现在找到使用 Collectors.toCollectionStream.collect 将数组转换为列表的示例。
CollectorsToCollection.java

package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectorsToCollection {
  public static void main(String[] args) {
     System.out.println("---Example-1---");		
     String[] persons = {"Mukesh", "Vishal", "Amar"};
     List&ltString> personList = Stream.of(persons).collect(Collectors.toCollection(ArrayList::new));
     personList.add("Mohit");
     personList.forEach(p-> System.out.print(p + " "));	

     System.out.println("\n---Example-2---");
     Book[] books = Book.getBooks();
     List&ltBook> bookList = Stream.of(books).collect(Collectors.toCollection(ArrayList::new));
     bookList.add(new Book("Learning Angular", 250));
     bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | ")); 	
	}
}

输出

---Example-1---
Mukesh Vishal Amar Mohit 
---Example-2---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | Learning Angular-250 |

2.3 原始数字数组转换为列表

要将原始数字数组转换为列表,我们需要分别使用 IntStream.boxed()LongStream.boxed()DoubleStream.boxed() 将这些数字装箱为 IntegerLongDouble。如果我们传递 int 数组,则 Arrays.stream 返回 IntStream。如果我们传递 long 数组,Arrays.stream 返回 LongStream ,对于 double 数据类型,我们得到 DoubleStream 。找到将 int 数组转换为 Integer 列表的示例示例。

CollectorsToListWithInt.java

package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectorsToListWithInt {
  public static void main(String[] args) {
    int[] nums = {12, 14, 16, 20};
    List&ltInteger> list = Arrays.stream(nums).boxed().collect(Collectors.&ltInteger&gttoList());
    list.add(30);
    list.forEach(i-> System.out.print(i + " "));
  }
}

输出

12 14 16 20 30

3. Java 5:使用 Collections.addAll

Collections.addAll 将所有指定元素添加到指定集合中。使用 Collections.addAll 我们可以将数组转换为列表。 Collections.addAll 是在 Java 5 中引入的。找到使用 Collections.addAll 将数组转换为列表的代码。
CollectionsAddAll.java

package com.concretepage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsAddAll {
  public static void main(String[] args) {
    System.out.println("---Example-1---");		
    String[] persons = {"Mukesh", "Vishal", "Amar"};
    List&ltString> personList = new ArrayList<>();
    Collections.addAll(personList, persons);	
    personList.add("Mohit");
    personList.forEach(p-> System.out.print(p + " "));

    System.out.println("\n---Example-2---");
    List&ltBook> bookList = new ArrayList<>();
    Book[] books = Book.getBooks();
    Collections.addAll(bookList, books);	
    bookList.add(new Book("Learning Angular", 250));
    bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | ")); 	  
  }
}

输出

---Example-1---
Mukesh Vishal Amar Mohit 
---Example-2---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | Learning Angular-250 |

4. Java 1.2:使用 Arrays.asList

1.Arrays.asList 返回由指定数组支持的固定大小列表。这将是一个不可变的列表,我们不能在其中添加任何元素。 Arrays.asList 是在 Java 1.2 中引入的。

String[] persons = {"Mukesh", "Vishal", "Amar"};
List&ltString> personList = Arrays.asList(persons);

2. 在上面的代码片段中,实例 personList 是不可变的。如果我们在其中添加任何元素,如下所示

personList.add("Mohit");

它将抛出以下异常。

Exception in thread "main" java.lang.UnsupportedOperationException

3. 要获得一个可变列表,我们可以使用 ArrayList 如下。

List&ltString> personList = new ArrayList<>(Arrays.asList(persons));

现在我们可以在其中添加新元素。

查找使用 Arrays.asList 将数组转换为列表的示例。
ArraysAsList.java

package com.concretepage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArraysAsList {
   public static void main(String[] args) {
	   System.out.println("---Example-1---");
	   String[] persons = {"Mukesh", "Vishal", "Amar"};
	   List&ltString> personList = Arrays.asList(persons);
	   personList.forEach(p-> System.out.print(p + " "));

	   System.out.println("\n---Example-2---");
	   personList = new ArrayList<>(Arrays.asList(persons));
	   personList.add("Mohit");
	   personList.forEach(p-> System.out.print(p + " "));
		 
	   System.out.println("\n---Example-3---");
	   Book[] books = Book.getBooks();
	   List&ltBook> bookList = Arrays.asList(books);
	   bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | "));

	   System.out.println("\n---Example-4---");
	   bookList = new ArrayList<>(Arrays.asList(books));
	   bookList.add(new Book("Learning Angular", 250));
	   bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | ")); 
   }
}

输出

---Example-1---
Mukesh Vishal Amar 
---Example-2---
Mukesh Vishal Amar Mohit 
---Example-3---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | 
---Example-4---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | Learning Angular-250 |

相关文章