java-stream

How to convert List to Map with indexes using stream - Java 8?

送分小仙女□ 提交于 2019-12-03 23:04:08
I've created method whih numerating each character of alphabet. I'm learning streams(functional programming) and try to use them as often as possible, but I don't know how to do it in this case: private Map<Character, Integer> numerateAlphabet(List<Character> alphabet) { Map<Character, Integer> m = new HashMap<>(); for (int i = 0; i < alphabet.size(); i++) m.put(alphabet.get(i), i); return m; } So, how to rewrite it using streams of Java 8? Misha Avoid stateful index counters like the AtomicInteger -based solutions presented in other answers. They will fail if the stream were parallel. Instead

Non-terminal forEach() in a stream?

会有一股神秘感。 提交于 2019-12-03 22:44:22
Sometimes when processing a Java stream() I find myself in need of a non-terminal forEach() to be used to trigger a side effect but without terminating processing. I suspect I could do this with something like .map(item -> f(item)) where the method f performs the side effect and returns the item to the stream, but it seems a tad hokey. Is there a standard way of handling this? Yes there is. It is called peek() (example from the JavaDoc ): Stream.of("one", "two", "three", "four") .peek(e -> System.out.println("Original value: " + e)) .filter(e -> e.length() > 3) .peek(e -> System.out.println(

Stream versus Iterator in entrySet of a Map

我的梦境 提交于 2019-12-03 22:36:20
To my understanding, the following code should print true , since both Stream and Iterator are pointing to the first element. However, when I run the following code it is printing false : final HashMap<String, String> map = new HashMap<>(); map.put("A", "B"); final Set<Map.Entry<String, String>> set = Collections.unmodifiableMap(map).entrySet(); Map.Entry<String, String> entry1 = set.iterator().next(); Map.Entry<String, String> entry2 = set.stream().findFirst().get(); System.out.println(entry1 == entry2); What is the reason of the different behavior? Both entries are referring to the same

Java 8 CompletableFuture , Stream and Timeouts

眉间皱痕 提交于 2019-12-03 22:25:02
问题 i'm trying to process some amount of data concurrently using CompletableFuture and Stream So far i have: public static void main(String[] args) throws InterruptedException, ExecutionException { System.out.println("start"); List<String> collect = Stream.of("1", "2", "3", "4", "5", "6", "7") .map(x -> CompletableFuture.supplyAsync(getStringSupplier(x))) .collect(Collectors.toList()) .stream() .map(CompletableFuture::join) .collect(Collectors.toList()); System.out.println("stop out!"); } public

Stream.findFirst different than Optional.of?

倖福魔咒の 提交于 2019-12-03 22:24:05
Lets say I have two classes and two methods: class Scratch { private class A{} private class B extends A{} public Optional<A> getItems(List<String> items){ return items.stream() .map(s -> new B()) .findFirst(); } public Optional<A> getItems2(List<String> items){ return Optional.of( items.stream() .map(s -> new B()) .findFirst() .get() ); } } Why does getItems2 compile while getItems gives compiler error incompatible types: java.util.Optional<Scratch.B> cannot be converted to java.util.Optional<Scratch.A> So when I get the value of the Optional returned by findFirst and wrap it again with

IntStream of chars to Strings - Java

会有一股神秘感。 提交于 2019-12-03 21:59:45
Is it possible to convert stream of chars str.chars() to stream with Strings, where each String contains 5 characters, for example? I don't think trying to combine elements from the characters is a good fit for Java streams without using some third party libraries. If you want a stream of 5 character substrings I would split them like this: String s = "1234567890123456789012345678901234567890"; IntStream.range(0, s.length()/5) .mapToObj(i -> s.substring(i*5, (i+1)*5)) .forEach(System.out::println); You can simply split you string into five character sized strings using String[] split = string

Nested stream exception

独自空忆成欢 提交于 2019-12-03 21:55:09
问题 I would like to return permutations of strings from all strings. When i use below code, i get java.lang.IllegalStateException: stream has already been operated upon or closed . Could you please tell me what is wrong with this approach ? public Stream<String> getMyPatterns( Stream<String> s1, Stream<String> s2, Stream<String> s3) { List<String> out = new ArrayList<String>(); s1.collect(Collectors.toList()).forEach(item1 -> { s2.collect(Collectors.toList()).forEach(item2 -> { s3.collect

Why System.out::println is slower than anonymous class implementation in Java 8?

[亡魂溺海] 提交于 2019-12-03 21:53:07
I was working with some Java 8 Stream APIs. I am confused to see the performance difference between below two solutions, that are just printing the contents of Stream . Solution 1: int[] array = new int[] { 0, 1, 2, 3, 4, 5 }; start = System.nanoTime(); Arrays.stream(array).forEach(System.out::println); System.out.println((System.nanoTime() - start) / 1000000.0f); Solution 2: int[] array = new int[] { 0, 1, 2, 3, 4, 5 }; start = System.nanoTime(); Arrays.stream(array).forEach(new IntConsumer() { @Override public void accept(int value) { System.out.println(value); } }); System.out.println(

Multiply 2 double[][] Matrices Using Streams

ε祈祈猫儿з 提交于 2019-12-03 20:28:49
I'm wondering what the most compact and efficient way to multiple 2 double[][] arrays matrices using streams. The approach should follow matrix multiplication rules as illustrated here: http://www.mathwarehouse.com/algebra/matrix/multiply-matrix.php Here's one way to do it using for loops ('this' is the first matrix'): final int nRows = this.getRowDimension(); final int nCols = m.getColumnDimension(); final int nSum = this.getColumnDimension(); final double[][] outData = new double[nRows][nCols]; // Will hold a column of "m". final double[] mCol = new double[nSum]; final double[][] mData = m

Encounter order preservation in java stream

六眼飞鱼酱① 提交于 2019-12-03 20:26:36
I have gone through related questions like How to ensure order of processing in java8 streams? , still ordering of output element is not completely clear to me. Therefore please clarify my following doubt. Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8 }; List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray)); listOfIntegers .parallelStream() .unordered() .forEachOrdered(e -> System.out.print(e + " ")); I think at least theoretically(or according to java specification) it can print in random order than 1, 2, 3, 4, 5, 6, 7, 8. Am I correct? One more related question- the decision