0

I am having issues understanding how to create an array of n objects in Java.

This is the constructor of class ServicePath as follows:

public ServicePath(String id) {
   this.id = id;
}

This is the elements of the array that I would like to create the objects.

String ServicePathArrays[] = {"SH11","SH13","SH17","SH110","SH111","SH112","SH115", ...}

I tried the following, but it creates it manually.

ServicePath[] servicePathArray = new ServicePath[ServicePathArrays.length];

For example, manually it creates the following

ServicePath[0] = new ServicePath("SH11");
ServicePath[1] = new ServicePath("SH13");
..
..

I would like to create it automatically using String ServicePathArrays in such way:

ServicePath[0].id = "SH11";
ServicePath[1].id = "SH12";
ServicePath[2].id = "SH13";
..
..
1
  • Are you looking for the most compact way of doing it? Commented Dec 20, 2017 at 11:18

2 Answers 2

1

This could be done using the functional behavior of jdk8+ :

String servicePathArray[] = {"SH11", "SH13", "SH17",
                             "SH110", "SH111", "SH112", "SH115"};
List<ServicePath> collection = Stream.of(servicePathArray)
                                     .map(ServicePath::new)
                                     .collect(Collectors.toList());

System.out.println(collection); 
Sign up to request clarification or add additional context in comments.

2 Comments

It's more succinct to have Stream.of(servicePathArray) than Arrays.asList(servicePathArray).stream(). And even more succinct is Stream.of("SH11", "SH13", ..., "SH115").
I agree :+1 for this hint
1
String ServicePathArrays[] = {"SH11","SH13","SH17","SH110","SH111","SH112","SH115", ...};
ServicePath[] servicePathArray = new ServicePath[ServicePathArrays.length];
for(int i = 0; i < ServicePathArrays.length; i++) {
    servicePathArray [i] = new ServicePath(ServicePathArrays[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.