Daniel Kaplan
Daniel Kaplan

Reputation: 67360

How do I call map() on an IntStream and return a different type?

I want to do this:

            IntStream.range(0, fileNames.size())
                .map(i -> "mvn deploy:deploy-file" +
                        " -DrepositoryId=" + REPO_ID +
                        " -Durl=" + REPO_URL +
                        " -Dfile=" + LIBS + fileNames.get(i) +
                        " -DgroupId=" + GROUP_ID +
                        " -DartifactId=" + artifactName.get(i) +
                        " -Dversion=" + versionNumbers.get(i) +
                        " -DgeneratePom=true;")
                .collect(Collectors.toList());

But this doesn't compile because map() passes in an int and returns an int. How do I map from int to String?

PS: Is there a more idiomatic way to write this code?

Upvotes: 2

Views: 205

Answers (1)

Daniel Kaplan
Daniel Kaplan

Reputation: 67360

IntStream has a mapToObj method for this. With its generics, no need to cast, either:

        IntStream.range(0, fileNames.size())
                .mapToObj(i -> "mvn deploy:deploy-file" +
                        " -DrepositoryId=" + REPO_ID +
                        " -Durl=" + REPO_URL +
                        " -Dfile=" + LIBS + fileNames.get(i) +
                        " -DgroupId=" + GROUP_ID +
                        " -DartifactId=" + artifactName.get(i) +
                        " -Dversion=" + versionNumbers.get(i) +
                        " -DgeneratePom=true")
                .map(s -> s + ";")
                .collect(Collectors.toList());

Upvotes: 2

Related Questions