I have 35 categories inside this list List<CategoriesModel> categoriesModelList;
, and I want to clone all names and put them inside this array String[] namesList
, I'm currently cloning names using this code but I want to ask is there any method can clone names from list to the specific array without creating a loop?
String[] namesList = new String[categoriesModelList.size()];
for (int i = 0; i < categoriesModelList.size(); i )
namesList[i] = categoriesModelList.get(i).getName();
CategoriesModel.java
public class CategoriesModel {
private int id;
private String name;
private boolean supportSubcategories;
public CategoriesModel(int id, String name, boolean supportSubcategories) {
this.id = id;
this.name = name;
this.supportSubcategories = supportSubcategories;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public boolean isSupportSubcategories() {
return supportSubcategories;
}
}
CodePudding user response:
You could use a stream:
String[] namesList = categoriesModelList.stream()
.map(CategoriesModel::getName)
.toArray(String[]::new);
CodePudding user response:
anyway you have to use loop operation.
but stream is more elegant.
String[] namesList = categoriesModelList.stream()
.map(CategoriesModel::getName)
.toArray(String[]::new);
CodePudding user response:
Use java.util.stream
for it:
String[] names = categoriesModelList.stream()
.map(category -> category.getName())
.collect(Collectors.toList())
.toArray(new String[]{});
Another variant avoid stream():
List<String> namesList = new LinkedList<>();
categoriesModelList.forEach(category -> namesList.add(category.getName()));
String[] names = namesList.toArray(new String[]{});
But this is just a workaround