java-stream

Java 8 IntStream for an int range?

自古美人都是妖i 提交于 2019-12-03 04:31:13
Is there a way to create an IntStream for a range of ints? Like if I wanted to stream values 1 to 1000, I could invoke some IntStream static factory to stream that range? IntStream.forRange(1, 1000).forEach(//do something... Never mind, I don't know why I missed it in the API documentation after reading it several times... IntStream.range(1,1000) 来源: https://stackoverflow.com/questions/28313726/java-8-intstream-for-an-int-range

Why does stream api is not designed for Exception handling?

谁说我不能喝 提交于 2019-12-03 04:04:57
Fixtures BiConsumer<Exception, Consumer<? super Integer>> NOTHING = (ex, unused) ->{/**/}; When I try to fix the bug that is reported by @Holger in this answer : Stream<Integer> stream = Stream.of(1, 2, 3); // v--- the bug I have already fixed, it will throws RuntimeException exceptionally(stream, NOTHING).collect(ArrayList::new, (l, x) -> { l.add(x); if (x < 4) throw new RuntimeException(); }, List::addAll); Everything is ok but when using Stream.of(T) the map(...) operation will be invoked infinitely, for example: List<Integer> result = exceptionally( // v--- infinitely call Stream.of("bad")

Collectors.toSet() and HashSet

天大地大妈咪最大 提交于 2019-12-03 03:23:45
问题 Take the following line of sample code: Set<String> someSet = someColletion.stream().map(p -> p.toString()).collect(Collectors.toSet()); I want a HashSet . Taking a debugger to the code, I am indeed getting a HashSet . I had a look at java.util.stream.Collectors.toSet() to observe the following code: public static <T> Collector<T, ?, Set<T>> toSet() { return new CollectorImpl<>((Supplier<Set<T>>) HashSet::new, Set::add, (left, right) -> { left.addAll(right); return left; }, CH_UNORDERED_ID);

Find element matching in 2 lists using java 8 stream

时光总嘲笑我的痴心妄想 提交于 2019-12-03 03:03:43
My case is: class Person { String id ; String name; String age; } List<Person> list1 = {p1,p2, p3}; List<Person> list2 = {p4,p5, p6}; I want to know if there is person in list1 that has the same name and age in list2 but don't mind about id . What is best and fast way? Define yourself a key object that holds and compares the desired properties. In this simple case, you may use a small list whereas each index corresponds to one property. For more complex cases, you may use a Map (using property names as keys) or a dedicated class: Function<Person,List<Object>> toKey=p -> Arrays.asList(p.getName

stream collect accumulator/combiner order

走远了吗. 提交于 2019-12-03 03:02:25
This is basically a follow-up of this answer of mine . Suppose that I am working on custom collector and supposing that the accumulator always will add some element to the collection returned by the supplier, is there any chance that when combiner is called, one of the intermediate results will be empty? An example is probably a lot simpler to understand. Suppose I have a List of numbers and I want to split it in List of Lists, where 2 is the separator. So for example I have 1, 2, 3, 4, 2, 8 , the result should be [[1], [3, 4], [8]] . This is not really complicated to achieve (don't judge the

Calculate weighted average with Java 8 streams

断了今生、忘了曾经 提交于 2019-12-03 03:00:27
How do I go about calculating weighted mean of a Map<Double, Integer> where the Integer value is the weight for the Double value to be averaged. eg: Map has following elements: (0.7, 100) // value is 0.7 and weight is 100 (0.5, 200) (0.3, 300) (0.0, 400) I am looking to apply the following formula using Java 8 streams, but unsure how to calculate the numerator and denominator together and preserve it at the same time. How to use reduction here? You can create your own collector for this task: static <T> Collector<T,?,Double> averagingWeighted(ToDoubleFunction<T> valueFunction, ToIntFunction<T>

Java 8: More efficient way of comparing lists of different types?

限于喜欢 提交于 2019-12-03 02:28:25
In a unit test, I want to verify that two lists contain the same elements. The list to test is build of a list of Person objects, where one field of type String is extracted. The other list contains String literals. One often finds the following code snippet to accomplish this task (see this answer ): List<Person> people = getPeopleFromDatabasePseudoMethod(); List<String> expectedValues = Arrays.asList("john", "joe", "bill"); assertTrue(people.stream().map(person -> person.getName()).collect(Collectors.toList()).containsAll(expectedValues)); The Person class is defiend as: public class Person

Java 8 stream short-circuit

女生的网名这么多〃 提交于 2019-12-03 01:41:34
Reading up a bit on Java 8, I got to this blog post explaining a bit about streams and reduction of them, and when it would be possible to short-circuit the reduction. At the bottom it states: Note in the case of findFirst or findAny we only need the first value which matches the predicate (although findAny is not guaranteed to return the first). However if the stream has no ordering then we’d expect findFirst to behave like findAny . The operations allMatch , noneMatch and anyMatch may not short-circuit the stream at all since it may take evaluating all the values to determine whether the

How to get a List<E> from a HashMap<String,List<E>>

馋奶兔 提交于 2019-12-03 01:18:23
I want to extract a List<E> from a Map<String,List<E>> ( E is a random Class) using stream() . I want a simple one-line method using java 8's stream. What I have tried until now : HashMap<String,List<E>> map = new HashMap<>(); List<E> list = map.values(); // does not compile list = map.values().stream().collect(Collectors.toList()); // does not compile map.values() returns a Collection<List<E>> not a List<E> , if you want the latter then you're required to flatten the nested List<E> into a single List<E> as follows: List<E> result = map.values() .stream() .flatMap(List::stream) .collect

Convert a for loop to concat String into a lambda expression

六月ゝ 毕业季﹏ 提交于 2019-12-03 01:17:01
I have the following for loop which iterates through a list of strings and stores the first character of each word in a StringBuilder . I would like to know how can I transform this to a lambda expression StringBuilder chars = new StringBuilder(); for (String l : list) { chars.append(l.charAt(0)); } Assuming you call toString() on the StringBuilder afterwards, I think you're just looking for Collectors.joining() , after mapping each string to a single-character substring: String result = list .stream() .map(s -> s.substring(0, 1)) .collect(Collectors.joining()); Sample code: import java.util.*