java-stream

How to separate a List by a condition using Java 8 streams

这一生的挚爱 提交于 2019-12-03 15:26:01
问题 Consider the following code: List<Integer> odd = new ArrayList<Integer>(); List<Integer> even = null; List<Integer> myList = Arrays.asList(1,2,3,4,5,6,7,8,9,10); even = myList.stream() .filter(item -> { if(item%2 == 0) { return true;} else { odd.add(item); return false; } }) .collect(Collectors.toList()); What I am trying to do here is get the even and odd values from a list into separate lists. The stream filter() method returns true for even items and the stream collector will collect them.

Java 8 streams and maps worth it?

爱⌒轻易说出口 提交于 2019-12-03 14:45:07
问题 It feels like java 8 streams and mapping functions are so verbose they aren't really an improvement. For example, I wrote some code that uses a collection to generate another, modified collection: private List<DartField> getDartFields(Class<?> model) { List<DartField> fields = new ArrayList<>(); for (Field field : model.getDeclaredFields()) { if (!Modifier.isStatic(field.getModifiers())) { fields.add(DartField.getDartField(field)); } } return fields; } This seems like the ideal use case for

Use Streams to return Boolean if all the List values in a Map are empty/not-empty

流过昼夜 提交于 2019-12-03 14:38:52
问题 Given a Map mapping a String to a List, is there a way to use Java Streams to return a Boolean where TRUE means one or more list had elements? If all lists in the map were empty, return FALSE. Map< String , List<String> > map = … Can use of Streams replace this conventional code? // See if any diffs were found. Loop through the Map, look at each List of diffs to see if non-empty. boolean anyElementsInAnyList = false; for (List<String> list : map.values () ) { if (!list.isEmpty()) {

One-to-one map with Java streams

扶醉桌前 提交于 2019-12-03 13:55:45
Having a little trouble using the Stream API to get a one to one mapping. Basically, say you've got a class. public class Item { private final String uuid; private Item(String uuid) { this.uuid = uuid; } /** * @return universally unique identifier */ public String getUuid() { return uuid; } } I'd like a Map<String, Item> for easy look up. But given a Stream<Item> there doesn't seem a simple way to arrive at that Map<String, Item> . Obviously, Map<String, List<Item>> ain't no thing: public static Map<String, List<Item>> streamToOneToMany(Stream<Item> itemStream) { return itemStream.collect

Getting only required objects from a list using Java 8 Streams

℡╲_俬逩灬. 提交于 2019-12-03 13:09:25
Consider a Parent class with the attributes attrib1 , attrib2 and List<Child> child with its corresponding getters and setters. The Child is another class with five attributes attrib1 - attrib5 with its corresponding getters and setters. Now I created a List<Parent> parent. Then I want to filter out a List<Parent> with following condition:- Child.Attrib1 > 10 ; So I created the following query by Java 8 streams. parent.stream().filter(e -> e.getChild().stream().anyMatch(c -> c.getAttrib1() > 10)); But the problem is I will get all the child in each Parent object. Here I want to get only those

How to short-circuit reduce on Stream?

≯℡__Kan透↙ 提交于 2019-12-03 12:52:47
Suppose I have a stream of boolean values and the reduce operation that I am writing is || (OR). Can I write it in a way such that the evaluation of at least some of the elements is abandoned if a true value is encountered? I am looking for some amount of optimization (perhaps if it is a parallel stream), not necessarily full optimization although the latter would be awesome. I suspect you want this type of construct. // stop when any element evaluates to true boolean any = stream.anyMatch(t -> t); You can check this with peek Stream.of(1, 2, 3, 4).peek(System.out::println).anyMatch(i -> i ==

Catching exceptions out of 'stream()' or 'parallelStream()' loses correct values

泄露秘密 提交于 2019-12-03 12:52:10
In the following code, when catching NumberFormatException out of for iteration, the strings in appropriate form appearing in strList before the first bad one (i.e., "illegal_3" ) have been parsed successfully (i.e., "1" and "2" have been parsed as integers 1 and 2 ). public void testCaughtRuntimeExceptionOutOfIteration() { List<String> strList = Stream.of("1", "2", "illegal_3", "4", "illegal_5", "6").collect(Collectors.toList()); List<Integer> intList = new ArrayList<>(); try{ for (String str : strList) { intList.add(Integer.parseInt(str)); } } catch (NumberFormatException nfe) { System.err

Find element matching in 2 lists using java 8 stream

丶灬走出姿态 提交于 2019-12-03 12:39:03
问题 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? 回答1: 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

Multiple aggregate functions in Java 8 Stream API

对着背影说爱祢 提交于 2019-12-03 12:29:32
I have a class defined like public class TimePeriodCalc { private double occupancy; private double efficiency; private String atDate; } I would like to perform the following SQL statement using Java 8 Stream API. SELECT atDate, AVG(occupancy), AVG(efficiency) FROM TimePeriodCalc GROUP BY atDate I tried : Collection<TimePeriodCalc> collector = result.stream().collect(groupingBy(p -> p.getAtDate(), .... What can be put into the code to select multiple attributes ? I'm thinking of using multiple Collectors but really don't know how to do so. To do it without a custom Collector (not streaming

Java 8 adding values of multiple property of an Object List

泪湿孤枕 提交于 2019-12-03 12:27:44
Lets say I have a class below with getters and setters but with only default constructor. Note: I'm not allowed to change the structure of this class. class Target { private String year; private String month; private String name; private double target; private double achieved; public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getMonth() { return month; } public void setMonth(String month) { this.month = month; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getTarget() {