java-stream

`map-based memoized` in Java8?

为君一笑 提交于 2019-12-11 03:58:47
问题 In my previous Question here Infinite Fibonacci Sequence with Memoized in Java 8 I asked how to write a code to define the infinite sequence of fibonacci in concise math manner with memoization with Java8 Stream. Thankfully, I've got an answer, and the code below seems to work well: LongStream fibs = Stream .iterate( new long[]{1, 1}, f -> new long[]{f[1], f[0] + f[1]} ) .mapToLong(f -> f[0]); fibs .limit(30) .forEach(System.out::println); 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

How to combine unlike streams in Java 8

故事扮演 提交于 2019-12-11 03:57:54
问题 I have a Set<DateCount> which I create using the following code. This creates a set of 7 DateCount objects with an initial count of 0, one for each day of the current week starting from the current day. // Create an initial Set of DateCount objects for the current week with counts of 0 Set<DateCount> dateCounts = IntStream.range(0, DAYS_IN_WEEK) .mapToObj(idx -> new DateTime().withTimeAtStartOfDay().plusDays(idx)) .map(dt -> new DateCount(dt.toDate(), 0L)) .collect(toSet()); I have a List

Java 8 stream - how to find parent entity from child?

隐身守侯 提交于 2019-12-11 02:45:43
问题 I have a scenario similar to: public class A { private String id; @ManyToMany private Set<B> bSet; // getters and setters } and public class B { private String id; // other attributes // getters and setters } How can I find an instance of A when I have an instance of B using the stream() API? I was trying something like: public A findAFromB(B b) { List<A> aList = aService.findAll(); Optional<A> matchingObject = aList.stream().filter({find a where a.getBSet().contains(b)}).getA(); return (A)

Calculating difference of two lists with duplicates

心不动则不痛 提交于 2019-12-11 01:06:47
问题 I have two lists. List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 2)); List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 3, 4)); I want to remove the elements contained in list2 from list1 , precisely as many times as they are contained in list2 . In the example above: when we remove elements in list 1 which exist in list 2, we should get as result [1, 2] (only one occurrence of 2 should be removed from list1 because list2 contains only one instance of 2 ). I tried with list1

Runtime complexity of Collectors#toList

牧云@^-^@ 提交于 2019-12-11 00:03:13
问题 In the Java library source code, the Collectors#toList method is defined like this: public static <T> Collector<T, ?, List<T>> toList() { return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add, (left, right) -> { left.addAll(right); return left; }, CH_ID); } We see BinaryOperator as third parameter of CollectorImpl 's contructor, which merges two sub-results in linear time. Does it mean, that in case of frequent usage of this function by Stream#collect method, we can gain

Is it possible to collect a stream to two different collections using one line?

匆匆过客 提交于 2019-12-10 22:39:24
问题 I have the following code: (simplified for bravity) public void search(Predicate<String> predicate, Elements elements) { List<SearchResult> searchResults = elements.stream() .filter(element -> predicate.test(element.ownText())) .map(element -> new SearchResult(element.ownText(), element.baseUri(),element.tagName())) .collect(Collectors.toList()); } But now, I want to have another list which would contain all filtered elements without the mapping. Is it possible to do that with a stream, or

Converting List<MyObject> to Map<String, List<String>> in Java 8 when we have duplicate elements and custom filter criteria

柔情痞子 提交于 2019-12-10 21:47:05
问题 I have an instances of Student class. class Student { String name; String addr; String type; public Student(String name, String addr, String type) { super(); this.name = name; this.addr = addr; this.type = type; } @Override public String toString() { return "Student [name=" + name + ", addr=" + addr + "]"; } public String getName() { return name; } public String getAddr() { return addr; } } And I have a code to create a map , where it store the student name as the key and some processed addr

Why is BufferedReader not closed when obtaining `Stream<String>` in try-with-resources?

牧云@^-^@ 提交于 2019-12-10 21:27:43
问题 The reader should be closed when a Stream is used in a try-with-resources. Given this: try(Stream<String> lines = new BufferedReader(reader).lines()) { return lines.map(it -> trim ? it.trim() : it) .collect(Collectors.toList()); } ... the reader is not being closed?? This test fails: AtomicBoolean closed = new AtomicBoolean(false); Reader r = new StringReader(" Line1 \n Line2") { @Override public void close() { super.close(); closed.set(true); } }; try(Stream<String> lines = new

Java Stream collect after flatMap returns List<Object> instead of List<String>

烂漫一生 提交于 2019-12-10 21:14:51
问题 I tried the following code using Java 8 streams: Arrays.asList("A", "B").stream() .flatMap(s -> Arrays.asList("X", "Y").stream().map(s1 -> s + s1)).collect(Collectors.toList()); What I get is a List<Object> while I would expect a List<String> . If I remove the collect and I try: Arrays.asList("A", "B").stream().flatMap(s -> Arrays.asList("X", "Y").stream().map(s1 -> s + s1)); I correctly get a Stream<String> . Where am I wrong? Can someone help me? Many thanks in advance. Edit: The problem is

When to use specialised stream methods over methods in the Collectors class or vice versa?

倾然丶 夕夏残阳落幕 提交于 2019-12-10 18:57:07
问题 We can see that the Collectors class contains factory methods for many common aggregation operations. to name a few summingXXX , averagingXXX , maxBy , minBy . These methods are actually duplicate functionality over calling methods on specialised streams. take for example IntStream, this has a sum() , average() , max() and min() respectively. Same goes for DoubleStream and LongStream. Every now and then I see people using the methods which belong to the Collectors class and specialized stream