java-8

Flattening a list of elements in Java 8 Optional pipeline

泪湿孤枕 提交于 2020-12-29 13:18:37
问题 I have a id value which can be null . Then I need to call some service with this id to get a list of trades and fetch the first not null trade from the list. Currently I have this working code Optional.ofNullable(id) .map(id -> service.findTrades(id)) .flatMap(t -> t.stream().filter(Objects::nonNull).findFirst()) .orElse(... default value...); Is it possible to implement a line with a flatMap call more elegantly? I don't want to put much logic in one pipeline step. Initially I expected to

Rewrite double nested for loop as a Java 8 stream

匆匆过客 提交于 2020-12-29 12:20:29
问题 I have the following Java method: public List<GrantedAuthority> toAuthorities(Set<Role> roles) { List<GrantedAuthority> authorities = new ArrayList<>(); if (null != roles) { for (Role role : roles) { for (Permission permission : role.getPermissions()) { authorities.add(new SimpleGrantedAuthority("ROLE_" + permission.getLabel())); } } } return authorities; } I'm trying to rewrite it using Java 8 streams. My best attempt thus far: public List<GrantedAuthority> toAuthorities(Set<Role> roles) {

Java 8 stream sum entries for duplicate keys

故事扮演 提交于 2020-12-29 12:12:50
问题 I am using Java 8 streams to group a list of entries by a certain key and then sorting the groups by date. What I would like to do in addition is to "collapse" any two entries within a group that have the same date and sum them up. I have a class like this (stripped down for example purposes) class Thing { private String key; private Date activityDate; private float value; ... } Then I'm grouping them like so: Map<String, List<Thing>> thingsByKey = thingList.stream().collect( Collectors

Java 8 epoch-millis time stamp to formatted date, how?

怎甘沉沦 提交于 2020-12-29 10:15:12
问题 Before Java-8 I got accustomed to always keep anything date/time related as milliseconds since Epoch and only ever deal with human readable dates/times on the way out, i.e. in a UI or a log file, or when parsing user generated input. I think this is still safe with Java-8, and now I am looking for the most concise way to get a formatted date out of a milliseconds time stamp. I tried df = Dateformatter.ofPattern("...pattern..."); df.format(Instant.ofEpochMilli(timestamp)) but it bombs out with

Java 8 epoch-millis time stamp to formatted date, how?

时光毁灭记忆、已成空白 提交于 2020-12-29 10:14:40
问题 Before Java-8 I got accustomed to always keep anything date/time related as milliseconds since Epoch and only ever deal with human readable dates/times on the way out, i.e. in a UI or a log file, or when parsing user generated input. I think this is still safe with Java-8, and now I am looking for the most concise way to get a formatted date out of a milliseconds time stamp. I tried df = Dateformatter.ofPattern("...pattern..."); df.format(Instant.ofEpochMilli(timestamp)) but it bombs out with

Optional vs if/else-if performance java 8

℡╲_俬逩灬. 提交于 2020-12-29 09:31:42
问题 Hello i have two samples of code if/else if/else statements private Object getObj(message) { if (message.getA() != null) return message.getA(); else if (message.getB() != null) return message.getB(); else if (message.getC() != null) return message.getC(); else return null; } Optional statements private Optional<Object> wrap(Object o){ return Optional.ofNullable(o); } private Object getObj(message) { return wrap(message.getA()) .orElseGet(() -> wrap(message.getB()) .orElseGet(() -> wrap

Why does the Duration class not have 'toSeconds()' method?

只愿长相守 提交于 2020-12-29 08:45:48
问题 I was looking at the Duration class in Java 8 and noticed that it does not have: long toSeconds(); But it has all other toXXXXX() to get days, hours, minutes, millis, nanos. I do see a getSeconds() method that returns the number of seconds within this duration object. There is also a get(TemporalUnit unit) method to get the duration as the requested time unit. But why not keep the toSeconds() method for consistency? 回答1: Let's look at what the docs say: This class models a quantity or amount

Split list of objects into multiple lists of fields values using Java streams

☆樱花仙子☆ 提交于 2020-12-29 07:51:33
问题 Let's say I have such object: public class Customer { private Integer id; private String country; private Integer customerId; private String name; private String surname; private Date dateOfBirth; } and I have a List<Customer> . I would like to split such list with Java streams so that I would get a list of ids List<Integer> , countries List<String> , customerIds List<Integer> etc. I know that I could do it as simple as making 6 streams such as: List<Integer> idsList = customerList.stream()

Java 8 Stream to find element in list

喜夏-厌秋 提交于 2020-12-29 05:52:25
问题 I have the following class: public class Item { int id; String name; // few other fields, contructor, getters and setters } I have a list of Items. I want to iterate through the list and find the instance which has a particular id. I'm trying to do it through streams. public void foobar() { List<Item> items = getItemList(); List<Integer> ids = getIdsToLookup(); int id, i = ids.size() - 1; while (i >= 0) { id = ids.get(i); Optional<Item> item = items .stream() .filter(a -> a.getId() == id)

Java 8 Stream to find element in list

夙愿已清 提交于 2020-12-29 05:51:33
问题 I have the following class: public class Item { int id; String name; // few other fields, contructor, getters and setters } I have a list of Items. I want to iterate through the list and find the instance which has a particular id. I'm trying to do it through streams. public void foobar() { List<Item> items = getItemList(); List<Integer> ids = getIdsToLookup(); int id, i = ids.size() - 1; while (i >= 0) { id = ids.get(i); Optional<Item> item = items .stream() .filter(a -> a.getId() == id)