java-stream

Performing specific operation on first element of list using Java8 streaming

风格不统一 提交于 2019-12-05 04:07:55
I want to perform certain operation on first element of my list and different operation for all remaining elements. Here is my code snippet: List<String> tokens = getDummyList(); if (!tokens.isEmpty()) { System.out.println("this is first token:" + tokens.get(0)); } tokens.stream().skip(1).forEach(token -> { System.out.println(token); }); Is there any more cleaner way to achieve this preferably using java 8 streaming API. Holger One way to express the intention is Spliterator<String> sp = getDummyList().spliterator(); if(sp.tryAdvance(token -> System.out.println("this is first token: "+token)))

Creating Map composed of 2 Lists using stream().collect in Java

会有一股神秘感。 提交于 2019-12-05 03:26:22
As for example, there are two lists: List<Double> list1 = Arrays.asList(1.0, 2.0); List<String> list2 = Arrays.asList("one_point_zero", "two_point_zero"); Using Stream, I want to create a map composed of these lists, where list1 is for keys and list2 is for values. To do it, I need to create an auxiliary list: List<Integer> list0 = Arrays.asList(0, 1); Here is the map: Map<Double, String> map2 = list0.stream() .collect(Collectors.toMap(list1::get, list2::get)); list0 is used in order list1::get and list2::get to work. Is there a simpler way without creation of list0? I tried the following code

What is the (kind of) inverse operation to Java's Stream.flatMap()?

与世无争的帅哥 提交于 2019-12-05 03:23:11
The Stream.flatMap() operation transforms a stream of a, b, c into a stream that contains zero or more elements for each input element, e.g. a1, a2, c1, c2, c3 Is there the opposite operations that batches up a few elements into one new one? It is not .reduce(), because this produces only one result It is not collect(), because this only fills a container (afaiu) It is not forEach(), because this has returns just void and works with side effects Does it exist? can I simulate it in any way? Finally I figured out that flatMap is its own "inverse" so to say. I oversaw that flatMap not necessarily

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

只谈情不闲聊 提交于 2019-12-05 02:53:15
问题 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 ? 回答1: 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 ;

How to enable “type information” for streams returned from methods?

痞子三分冷 提交于 2019-12-05 02:47:05
Since a few versions, IntelliJ has a very helpful feature: when you put the individual method calls of a stream() statement on separate lines, IntelliJ puts type information on each line: But when you don't call stream() directly, like when it is returned from another method, that information is omitted: Is there a way to convince IntelliJ to show such type information for such situations, too? As pure text, with manually inserted comments to "show" the problem with pure text: public Stream<Entry<String, String>> withTypeInformation() { return generateMap() // Map<String, String> .entrySet() /

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

非 Y 不嫁゛ 提交于 2019-12-05 02:43:18
问题 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:

How to preserve newlines while reading a file using stream - java 8

拈花ヽ惹草 提交于 2019-12-05 02:24:56
try (Stream<String> lines = Files.lines(targetFile)) { List<String> replacedContent = lines.map(line -> StringUtils.replaceEach(line,keys, values)) .parallel() .collect(Collectors.toList()); Files.write(targetFile, replacedContent); } I'm trying to replace multiple text patterns in each line of the file. But I'm observing that "\r\n"(byte equivalent 10 and 13) is being replaced with just "\r"(just 10) and my comparison tests are failing. I want to preserve the newlines as they are in the input file and don't want java to touch them. Could anyone suggest if there is a way to do this without

ignore exception and continue & counting files in a directory

℡╲_俬逩灬. 提交于 2019-12-05 02:16:55
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 following class: public class Utils extends SimpleFileVisitor<Path> { private long count; @Override

Convert String list to sorted Map String length as key

为君一笑 提交于 2019-12-05 02:08:37
问题 I have a List<String> and I have to convert it to Map , by grouping same length String s into a List , using String length as the key in, sorted order. It can be done using - Map<Integer, List<String>> result = new TreeMap<>(); for (String str : list) { if (!result.containsKey(str.length())) { result.put(str.length(), new ArrayList<>()); } result.get(str.length()).add(str); } How can we do it using Java 8 streams? 回答1: You could do it with streams: Map<Integer, List<String>> result = list

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

陌路散爱 提交于 2019-12-05 01:55:12
问题 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