Java 8 List into Map
Based on Collectors documentation it’s as simple as: Map<String, Choice> result = choices.stream().collect(Collectors.toMap(Choice::getName, Function.identity()));
Based on Collectors documentation it’s as simple as: Map<String, Choice> result = choices.stream().collect(Collectors.toMap(Choice::getName, Function.identity()));
The cleanest way is to start from a stream of indices: String[] names = {“Sam”, “Pamela”, “Dave”, “Pascal”, “Erik”}; IntStream.range(0, names.length) .filter(i -> names[i].length() <= i) .mapToObj(i -> names[i]) .collect(Collectors.toList()); The resulting list contains “Erik” only. One alternative which looks more familiar when you are used to for loops would be to maintain an ad … Read more
There actually is a trick how to execute a parallel operation in a specific fork-join pool. If you execute it as a task in a fork-join pool, it stays there and does not use the common one. final int parallelism = 4; ForkJoinPool forkJoinPool = null; try { forkJoinPool = new ForkJoinPool(parallelism); final List<Integer> primes … Read more
Operations takeWhile and dropWhile have been added to JDK 9. Your example code IntStream .iterate(1, n -> n + 1) .takeWhile(n -> n < 10) .forEach(System.out::println); will behave exactly as you expect it to when compiled and run under JDK 9. JDK 9 has been released. It is available for download here: JDK 9 Releases.
I needed this as well so I just took the source code from b93 and put it in a “util” class. I had to modify it slightly to work with the current API. For reference here’s the working code (take it at your own risk…): public static<A, B, C> Stream<C> zip(Stream<? extends A> a, Stream<? … Read more
Java 8 Distinct by property
tradeFileInstances.stream() .collect(Collectors.groupingBy(TradeFileInstance::getTradeFileConfig)); Assuming that TradeFileConfig overrides equals/hashCode
You could do: List<Person> res = IntStream.range(0, firstName.size()) .mapToObj(i -> new Person(firstName.get(i), lastName.get(i))) .collect(Collectors.toList()); However this is assuming both List‘s are the same size This solution uses IntStream::range to generate a Stream of indices for the two List‘s
You are missing the map operator here. You have to add map operator to the stream processing pipeline before collecting it. Here’s how it looks. objList.stream().map(Obj::val).collect(Collectors.joining(“.”));
First of all, the existing solution with a loop is just fine. Simply translating it to a solution that uses streams is not an improvement. Here’s how I would do it. NB: this is not tested. // Naive version List<String> nameList1 = Arrays.asList(“Bill”, “Steve”, “Mark”); List<String> nameList2 = Arrays.asList(“Steve Jobs”, “Mark”, “Bill”); List<String> matchList = … Read more