java-stream

Complexity of grouping in Java8

橙三吉。 提交于 2019-12-04 03:09:44
I would like to learn the time complexity of the given statement below.(In Java8) list.stream().collect(groupingBy(...)); Any idea? There is no general answer to that question, as the time complexity depends on all operations. Since the stream has to be processed entirely, there is a base time complexity of O(n) that has to be multiplied by the costs of all operations done per element. This, assuming that the iteration costs itself are not worse than O(n) , which is the case for most stream sources. So, assuming no intermediate operations that affect the time complexity, the groupingBy has to

Call constructor with parameter inside Java stream with lambda

浪尽此生 提交于 2019-12-04 03:02:03
问题 I want to call a constructor for MySortedSet that takes in a Comparator c as a parameter. How can I modify this to do so? public MySortedSet<E> subSet(E fromElement, E toElement) { return list.stream() .filter(x -> (list.indexOf(x) <= list.indexOf(fromElement) && list.indexOf(x) < list.indexOf(toElement))) .collect(Collectors.toCollection(MySortedSet<E> :: new)); } 回答1: You can’t use method references if you want to pass additional captured values as parameters. You will have to use a lambda

What is more efficient: sorted stream or sorting a list?

不羁的心 提交于 2019-12-04 02:47:02
问题 Assume we have some items in a collection and we want to sort them using certain comparator, expecting result in a list: Collection<Item> items = ...; Comparator<Item> itemComparator = ...; One of the approaches is to sort items in a list, something like: List<Item> sortedItems = new ArrayList<>(items); Collections.sort(sortedItems, itemComparator); Anothe approach is using a sorted stream: List<Item> sortedItems = items .stream() .sorted(itemComparator) .collect(Collectors.toList()); I

How to convert Array to HashMap using Java 8 Stream

偶尔善良 提交于 2019-12-04 02:38:49
I am writing a function to convert array to Map using Java 8 Stream. Here is what I wanted public static <K, V> Map<K, V> toMap(Object... entries) { // Requirements: // entries must be K1, V1, K2, V2, .... ( even length ) if (entries.length % 2 == 1) { throw new IllegalArgumentException("Invalid entries"); } // TODO Arrays.stream(entries).???? } Valid usages Map<String, Integer> map1 = toMap("k1", 1, "k2", 2); Map<String, String> map2 = toMap("k1", "v1", "k2", "v2", "k3", "v3"); Invalid usages Map<String, Integer> map1 = toMap("k1", 1, "k2", 2, "k3"); Any helps? Thanks! You may use public

SecurityException from I/O code in a parallel stream

让人想犯罪 __ 提交于 2019-12-04 02:38:24
I have no way to explain this one, but I found this phenomenon in somebody else's code: import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.util.stream.Stream; import org.junit.Test; public class TestDidWeBreakJavaAgain { @Test public void testIoInSerialStream() { doTest(false); } @Test public void testIoInParallelStream() { doTest(true); } private void doTest(boolean parallel) { Stream<String> stream = Stream.of("1", "2", "3"); if (parallel) { stream = stream.parallel(); } stream.forEach(name -> { try { Files.createTempFile(name, ".dat"); }

Java 8 reference to a static method vs. instance method

a 夏天 提交于 2019-12-04 02:34:12
say I have the following code public class A { int x; public boolean is() {return x%2==0;} public static boolean is (A a) {return !a.is();} } and in another class... List<A> a = ... a.stream().filter(b->b.isCool()); a.stream().filter(A::is); //would be equivalent if the static method is(A a) did not exist the question is how do I refer to the instance method version using the A::is type notation? Thanks a lot nosid In your example, both the static and the non-static method are applicable for the target type of the filter method. In this case, you can't use a method reference, because the

Why can I collect a parallel stream to an arbitrarily large array but not a sequential stream?

我是研究僧i 提交于 2019-12-04 02:26:29
From answering this question , I ran into a peculiar feature. The following code works as I assumed it would (the first two values within the existing array would be overridden): Integer[] newArray = Stream.of(7, 8) .parallel() .toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6}); System.out.println(Arrays.toString(newArray)); Output: [7, 8, 3, 4, 5, 6] However, attempting this with a sequential stream throws an IllegalStateException : Integer[] newArray = Stream.of(7, 8) .toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6}); System.out.println(Arrays.toString(newArray)); Output: Exception in thread

Java stream reduce

我与影子孤独终老i 提交于 2019-12-04 02:25:49
I have the following example data set that I want to transform / reduce using Java stream api based on direction's value Direction int[] IN 1, 2 OUT 3, 4 OUT 5, 6, 7 IN 8 IN 9 IN 10, 11 OUT 12, 13 IN 14 to Direction int[] IN 1, 2, OUT 3, 4, 5, 6, 7 IN 8, 9, 10, 11 OUT 12, 13 IN 14 code that I've written so far enum Direction { IN, OUT } class Tuple { Direction direction; int[] data; public Tuple merge(Tuple t) { return new Tuple(direction, concat(getData(), t.getData())); } } private static int[] concat(int[] first, int[] second) { int[] result = Arrays.copyOf(first, first.length + second

Convert List of Strings into Map using Java-8 Streams API

最后都变了- 提交于 2019-12-04 02:18:11
问题 I have List List<String> cars = Arrays.asList("Ford", "Focus", "Toyota", "Yaris","Nissan", "Micra", "Honda", "Civic"); Now, can I convert this List into Map where I get ford = focus, Toyota = yaris, Nisan = Micra, Honda = Civic using Java 8 Streams API? 回答1: Here is an example on how you could do it : Map<String, String> carsMap = IntStream.iterate(0, i -> i + 2).limit(cars.size() / 2) .boxed() .collect(Collectors.toMap(i -> cars.get(i), i -> cars.get(i + 1))); Basically, just iterates over

Conditionally add an operation to a Java 8 stream

强颜欢笑 提交于 2019-12-04 02:13:55
I'm wondering if I can add an operation to a stream, based off of some sort of condition set outside of the stream. For example, I want to add a limit operation to the stream if my limit variable is not equal to -1 . My code currently looks like this, but I have yet to see other examples of streams being used this way, where a Stream object is reassigned to the result of an intermediate operation applied on itself: // Do some stream stuff stream = stream.filter(e -> e.getTimestamp() < max); // Limit the stream if (limit != -1) { stream = stream.limit(limit); } // Collect stream to list stream