I have little problem with code design that use new streaming API from Java 8. I would like to learn new things and one of the task is:
Reject max and min from list. List not contains duplicates.
Looks simple? Nope... My code:
List<Integer> ranges = Lists.newArrayList(new Range(1, 15));
List<Integer> collect = ranges.stream()
.filter(x -> x != ranges.stream()
.mapToInt(Integer::intValue)
.max()
.getAsInt())
.filter(x -> x != ranges.stream()
.mapToInt(Integer::intValue)
.min()
.getAsInt())
.collect(Collectors.toList());
assertThat(collect).hasSize(13); // OK
assertThat(collect).isEqualTo(Lists.newArrayList(new Range(2,14))); // OK
this code is good (if only we dont have duplicates of min/max, but this is not a core problem here) but problem is that I use here three streams. First is main stream, second to remove max and third to remove min. Is there any possibility to do this task in one stream?
//edit: Very primitive Scala version:
val list = List.range(1, 15).sortWith(_>_).tail.reverse.tail
with additional sort because we could have shuiffeled list.
.filter(x -> x != ranges.get(0)).filter(x -> x != ranges.get(ranges.size()-1))
– DorsoList<Integer> collect = ranges.stream().sorted().collect(Collectors.toList()).subList(1, ranges.size()-1);
then be an option? It's at least closer to the Scala approach... – Lenny