Checking range of List in forEach lambda loop Java 8
foreach, java, java-8, lambda
Solution
There's no direct way to get the index of a stream item while you're processing the items themselves. There are several alternatives, though.
One way is to run the stream over the indexes and then get the elements from the list. For each element index it maps `i` to the i'th element and appends a "," for all indexes except the last:
IntStream.range(0, objList.size())
.mapToObj(i -> objList.get(i) + (i < objList.size()-1 ? "," : ""))
.forEach(System.out::print);
A second, more concise variation is to special case the first element instead of the last one:
IntStream.range(0, objList.size())
.mapToObj(i -> (i > 0 ? "," : "") + objList.get(i))
.forEach(System.out::print);
A third way is to use the particular `reduce` operation that is applied "between" each two adjacent elements. The problem with this technique is that it does O(n^2) copying, which will become quite slow for large streams.
System.out.println(objList.stream().reduce((a,b) -> a + "," + b).get());
A fourth way is to special-case the last element by limiting the stream to length n-1. This requires a separate print statement, which isn't as pretty though:
objList.stream()
.limit(objList.size()-1)
.map(s -> s + ",")
.forEach(System.out::print);
System.out.print(objList.get(objList.size()-1));
A fifth way is similar to the above, special-casing the first element instead of the last:
System.out.print(objList.get(0));
objList.stream()
.skip(1)
.map(s -> "," + s)
.forEach(System.out::print);
Really, though the point of the `joining` collector is to do this ugly and irritating special-casing for you, so you don't have to do it yourself.
Problem
I want to learn how I can check the range of a list in java 8. For example, My Code: ``` List<String> objList = new ArrayList<>(); objList.add("Peter"); objList.add("James"); objList.add("Bart"); objList.stream().map((s) -> s + ",").forEach(System.out::print); ``` My out come is ``` Peter,James,Bart, ``` but I want to know how I can get rid of the last , Note: I know I must use filter here , yet I do not know how and I know there is another way to solve this which is as follows ``` String result = objList.stream() .map(Person::getFirstName) .collect(Collectors.joining(",")); ``` yet I want to know how to check the range and get rid of , in my first code.