java-stream

Why many Java Stream interface methods use lower bounded wildcard in parameters instead of generic type?

流过昼夜 提交于 2019-12-03 20:14:53
Many Java Stream interface methods use lower bounded wildcard in parameters for example Stream<T> filter(Predicate<? super T> pred) and void forEach(Consumer<? super T> action) What is the advantage of using Predicate<? super T> over Predicate<T> here? I understand, with Predicate<? super T> as parameter, Predicate object of T and super types can be passed into the method but i can't think of a situation where a Predicate of super type needed over the specific type? For example if i have a Stream<Integer> i can pass Predicate<Integer>, Predicate<Number>, and Predicate<Object> objects as

stream().collect(Collectors.toSet()) vs stream().distinct().collect(Collectors.toList())

北战南征 提交于 2019-12-03 20:11:50
If i have a list (~200 elements) of objects, with only few unique objects (~20 elements). I want to have only unique values. Between list.stream().collect(Collectors.toSet()) and list.stream().distinct().collect(Collectors.toList()) which is more efficient wrt latency and memory consumption ? Eugene While the answer is pretty obvious - don't bother with these details of speed and memory consumption for this little amount of elements and the fact that one returns a Set and the other a List ; there are some interesting small details (interesting IMO). Suppose you are streaming from a source that

Java 8 Stream mixing two elements

有些话、适合烂在心里 提交于 2019-12-03 20:07:21
问题 I have a many objects of type Slot in an array list. Slot class is as shown below- Slot{ int start; int end; } let the list of type List<Slot> be called slots . The slots are sorted based on start time. End time of one slot may be equal to start time of next slot, but they would never overlap. Is there any possible way in which I can iterate over this list using Java 8 streams, and combine two slots if end time of one matches start time of next and output them into an ArrayList ? 回答1: Such

Java 8 Streams - Timeout?

拜拜、爱过 提交于 2019-12-03 19:11:28
问题 I want to loop over a huge array and do a complicated set of instructions that takes a long time. However, if more than 30 seconds have passed, I want it to give up. ex. final long start = System.currentTimeMillis(); myDataStructure.stream() .while(() -> System.currentTimeMillis() <= start + 30000) .forEach(e -> { ... }); I want to avoid just saying return inside the forEach call if a certain condition is met. 回答1: If iterating the stream or array in this case is cheap compared to actually

Solve no final variable inside Java 8 Stream

99封情书 提交于 2019-12-03 18:29:39
Is there is a way to convert the following code to Java 8 Stream. final List ret = new ArrayList(values.size()); double tmp = startPrice; for (final Iterator it = values.iterator(); it.hasNext();) { final DiscountValue discountValue = ((DiscountValue) it.next()).apply(quantity, tmp, digits, currencyIsoCode); tmp -= discountValue.getAppliedValue(); ret.add(discountValue); } Java 8 streams complains about no final variable tmp ? Is there a way to solve such situations ? Local variable tmp defined in an enclosing scope must be final or effectively final First, change the code to use generics and

how to find maximum value from a Integer using stream in java 8?

狂风中的少年 提交于 2019-12-03 18:22:01
问题 I have a list of Integer list and from the list.stream() I want the maximum value. What is the simplest way? Do I need comparator? 回答1: You may either convert the stream to IntStream : OptionalInt max = list.stream().mapToInt(Integer::intValue).max(); Or specify the natural order comparator: Optional<Integer> max = list.stream().max(Comparator.naturalOrder()); Or use reduce operation: Optional<Integer> max = list.stream().reduce(Integer::max); Or use collector: Optional<Integer> max = list

How to add inner elements of Map when keys are duplicate with Java Stream API

陌路散爱 提交于 2019-12-03 17:17:43
I have a List of List<Map<String, Object>> like this [ {"A": 50, "B": 100, "C": 200, "D": "Auction" }, { "A": 101322143.24, "B": 50243301.2, "C": 569, "D": "Sold Promissory Buyer" }, { "A": 500, "B": 1000, "C": 1500, "D": "Auction" }] I am using this stream API method to convert this list into Map finalSalesReportForSoldProperty.stream().collect(Collectors.toMap(tags -> ((String) tags.get("D")).replaceAll("[\\- ]", ""), Function.identity())); But it throws me java.lang.IllegalStateException: Duplicate key exception, because my list has duplicate keys I want to add the inner elements of

Sort Map<String, Long> by value reversed

放肆的年华 提交于 2019-12-03 17:00:49
I have a Map<String, Long> map which I want to sort by the Long value in reversed order using the features of Java 8. With Google I found this thread which provides this solution Map<String, Long> sortedMap = map.entrySet().stream() .sorted(comparing(Entry::getValue)) .collect(toMap(Entry::getKey, Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new)); If I want to have the order reversed in the comments it says to use comparing(Entry::getValue).reversed() instead of comparing(Entry::getValue) . However, the code doesn't work. But with this little adaption it does: Map<String, Long> sortedMap =

Stream closeable resource with Spring MVC

ε祈祈猫儿з 提交于 2019-12-03 15:31:08
After having read this article , I wish to use Spring to stream database query results directly to a JSON response to ensure constant-memory usage (no greedy loading of a List in memory). Similar to what is done in the article with Hibernate, I assembled a greetingRepository object which returns a stream of the database contents based on a JdbcTemplate . In that implementation, I create an iterator over the queried ResultSet , and I return the stream as follows: return StreamSupport.stream(spliterator(), false).onClose(() -> { log.info("Closing ResultSetIterator stream"); JdbcUtils

Using Java 8 Stream Reduce to return List after performing operation on each element using previous elements values

元气小坏坏 提交于 2019-12-03 15:27:33
I'm new to Streams and Reduce so I'm trying it out and have hit a problem: I have a list of counters which have a start counter and end counter. The startcounter of an item is always the endcounter of the previous. I have a list of these counters listItems which I want to loop through efficiently, filter out inactive records and then reduce the list into a new List where all the StartCounters are set. I have the following code: List<CounterChain> active = listItems.stream() .filter(e -> e.getCounterStatus() == CounterStatus.ACTIVE) .reduce(new ArrayList<CounterChain>(), (a,b) -> { b