java-stream

ignore exception and continue & counting files in a directory

烈酒焚心 提交于 2019-12-22 04:01:39
问题 The following snippet of code counts the number of files in a directory: Path path = ...; .... long count = 0; try { count = Files.walk(path).parallel().filter(p -> !Files.isDirectory(p)).count(); } catch (IOException ex) { System.out.println(ex.getMessage()); } The code above fails to get the number of files, if an exception is thrown. The question is: How do I ignore the exception and continue counting the number of files. In Java 7 : I have used Files.walkFileTree(path, utils) , with the

Java Streams: get values grouped by inner map key

不问归期 提交于 2019-12-22 03:23:16
问题 I have Map<A, Map<B, C>> and I want to get Map<B, List<C>> from it using Java Streams. I try to do it as follows: public <A, B, C> Map<B, List<C>> groupsByInnerKey(Map<A, Map<B, C>> input) { return input.values() .stream() .flatMap(it -> it.entrySet().stream()) .collect(Collectors.groupingBy(Map.Entry::getKey)); } What I expect: flatMap gives a Stream of Map.Entry<B, C> collect(Collectors.groupingBy(...)) takes function which is applied to Map.Entry<B, C> and returns B , thus it collects

Cannot make filter->forEach->collect in one stream?

天大地大妈咪最大 提交于 2019-12-22 03:12:05
问题 I want to achieve something like this: items.stream() .filter(s-> s.contains("B")) .forEach(s-> s.setState("ok")) .collect(Collectors.toList()); filter, then change a property from the filtered result, then collect the result to a list. However, the debugger says: Cannot invoke collect(Collectors.toList()) on the primitive type void . Do I need 2 streams for that? 回答1: The forEach is designed to be a terminal operation and yes - you can't do anything after you call it. The idiomatic way would

How to apply multiple Filters on Java Stream?

寵の児 提交于 2019-12-22 01:44:55
问题 I have to filter a Collection of Objects by a Map, which holds key value pairs of the Objects field names and field values. I am trying to apply all filters by stream().filter(). The Objects are actually JSON, therefore the Map holds the names of its variables as well as the value they have to contain in order to be accepted, but for simplicity reasons and because its not relevant to the question I wrote a simple Testclass for simulating the behaviour: public class TestObject { private int

How can I create a Stream<String[]> with only one element with Stream.of?

你离开我真会死。 提交于 2019-12-22 01:33:47
问题 Using Stream.of to create generic streams is very convenient, but what if I want to create a Stream<String[]> of only one element? Let’s say I have: String[] tropicalFruits = new String[] {"pineapple", "banana", "mango"}; String[] fruits = new String[] {"melon", "peach", "apple"}; Then Stream.of(tropicalFruits, fruits) produces a Stream<String[]> of two elements. How can I achieve the same for a stream of a single element? If I try: Stream<String[]> fruityStream = Stream.of(tropicalFruits); I

Java 8 stream - sum of objects

核能气质少年 提交于 2019-12-22 01:28:23
问题 Let's say I have a list of objects implementing below interface: public interface Summable<T> { T add(T o1); } Let's say I have also some class which is able to sum these objects: public class Calculator<T extends Summable<T>> { public T sum(final List<T> objects) { if (null == objects) { throw new IllegalArgumentException("Ups, list of objects cannot be null!"); } T resultObject = null; for (T object : objects) { resultObject = object.add(resultObject); } return resultObject; } } How can I

Java List<Map<String, Long>> sum of group by of map key

▼魔方 西西 提交于 2019-12-21 23:17:08
问题 I have a: List<Map<String, Long>> items = new ArrayList<>(); I would like to get a Map in which the key is grouped by, and the value is the sum. Example: List Item 0 foo -> 1 bar -> 2 Item 1 foo -> 4 bar -> 3 Result: Map foo -> 5 bar -> 5 I know how to do this the "long" way, but was trying to discover a lambda/streaming/groupby approach using the java 8 features. any thoughts? 回答1: You can use groupingBy collector: import static java.util.stream.Collectors.groupingBy; import static java.util

Group, Collectors, Map (Int to String), Map (Map to Object)

时光总嘲笑我的痴心妄想 提交于 2019-12-21 22:48:43
问题 This is a continuation of my previous question at Group, Sum byType then get diff using Java streams. As suggested, I should post as a separate thread instead of updating the original one. So with my previous set of question, I have achieved that, and now, with the continuation. Background: I have the following dataset Sample(SampleId=1, SampleTypeId=1, SampleQuantity=5, SampleType=ADD), Sample(SampleId=2, SampleTypeId=1, SampleQuantity=15, SampleType=ADD), Sample(SampleId=3, SampleTypeId=1,

Java Streams — How to perform an intermediate function every nth item

Deadly 提交于 2019-12-21 20:51:03
问题 I am looking for an operation on a Stream that enables me to perform a non-terminal (and/or terminal) operation every nth item. Although I use a stream of primes for example, the stream could just as easily be web-requests, user actions, or some other cold data or live feed being produced. From this: Duration start = Duration.ofNanos(System.nanoTime()); IntStream.iterate(2, n -> n + 1) .filter(Findprimes::isPrime) .limit(1_000_1000 * 10) .forEach(System.out::println); System.out.println(

Lazy CSV Filtering / Parsing - Increasing Performance

有些话、适合烂在心里 提交于 2019-12-21 20:39:35
问题 Lazy Filtering CSV Files I had the need to filter through millions of log records, stored as numerous CSV files. The size of the records greatly exceeded my available memory so I wanted to go with a lazy approach. Java 8 Streams API With jdk8 we have the Streams API which paired with Apache commons-csv allows us to easily accomplish this. public class LazyFilterer { private static Iterable<CSVRecord> getIterable(String fileName) throws IOException { return CSVFormat .DEFAULT