java-stream

Java Stream: get latest version of user records

允我心安 提交于 2019-12-05 14:35:21
I have a list of User objects, defined as follows: public class User { private String userId; // Unique identifier private String name; private String surname; private String otherPersonalInfo; private int versionNumber; } public User(String userId, String name, String surname, String otherPersonalInfo, int version) { super(); this.name = name; this.surname = surname; this.otherPersonalInfo = otherPersonalInfo; this.version = version; } } Example list: List<User> users = Arrays.asList( new User("JOHNSMITH", "John", "Smith", "Some info", 1), new User("JOHNSMITH", "John", "Smith", "Updated info"

How do I map this in Java 8 using the stream API?

对着背影说爱祢 提交于 2019-12-05 14:35:19
Ok, so I have a List<Person> . and each Person has a List<String> that is a list of phone numbers that that person owns. So this is the basic structure: public class Person { private String name; private List<String> phoneNumbers; // constructors and accessor methods } I would like to create a Map<String, Person> where the key is each phone number that the person owns, and the value is the actual person. So to explain better. If I had this List<Person> : Person bob = new Person("Bob"); bob.getPhoneNumbers().add("555-1738"); bob.getPhoneNumbers().add("555-1218"); Person john = new Person("John"

Is use of AtomicInteger for indexing in Stream a legit way?

↘锁芯ラ 提交于 2019-12-05 14:11:42
I would like to get an answer pointing out the reasons why the following idea described below on a very simple example is commonly considered bad and know its weaknesses. I have a sentence of words and my goal is to make every second one to uppercase. My starting point for both of the cases is exactly the same: String sentence = "Hi, this is just a simple short sentence"; String[] split = sentence.split(" "); The traditional and procedural approach is: StringBuilder stringBuilder = new StringBuilder(); for (int i=0; i<split.length; i++) { if (i%2==0) { stringBuilder.append(split[i]); } else {

Limit groupBy in Java 8

余生颓废 提交于 2019-12-05 14:07:06
问题 How can I limit groupBy by each entry? For example (based on this example: stream groupBy): studentClasses.add(new StudentClass("Kumar", 101, "Intro to Web")); studentClasses.add(new StudentClass("White", 102, "Advanced Java")); studentClasses.add(new StudentClass("Kumar", 101, "Intro to Cobol")); studentClasses.add(new StudentClass("White", 101, "Intro to Web")); studentClasses.add(new StudentClass("White", 102, "Advanced Web")); studentClasses.add(new StudentClass("Sargent", 106, "Advanced

Create Java 8 Stream from ArrayNode

心已入冬 提交于 2019-12-05 13:25:07
问题 Is it possible to create stream from com.fasterxml.jackson.databind.node.ArrayNode ? I tried: ArrayNode files = (ArrayNode) json.get("files"); Stream<JsonNode> stream = Stream.of(files); But it will actually give stream of one element, the initial ArrayNode object. Correct result should be Stream<JsonNode> , can I achieve it? 回答1: ArrayNode implements Iterable . Iterable has a spliterator() method. You can create a sequential Stream from a Spliterator using StreamSupport.stream(spliterator,

Non-terminal forEach() in a stream?

眉间皱痕 提交于 2019-12-05 13:18:13
问题 Sometimes when processing a Java stream() I find myself in need of a non-terminal forEach() to be used to trigger a side effect but without terminating processing. I suspect I could do this with something like .map(item -> f(item)) where the method f performs the side effect and returns the item to the stream, but it seems a tad hokey. Is there a standard way of handling this? 回答1: Yes there is. It is called peek() (example from the JavaDoc): Stream.of("one", "two", "three", "four") .peek(e -

Infinite Fibonacci Sequence with Memoized in Java 8

僤鯓⒐⒋嵵緔 提交于 2019-12-05 13:17:36
Firstly, I'm a JavaScript programmer, and fairly new to Java8 and trying the new functional feature. Since I expertise JS coding, I implemented my own JS lazy-functional library for proof of concept. https://github.com/kenokabe/spacetime Using the library, I could write Infinite sequence of Natural numbers and Fibonacci as below: JavaScript var spacetime = require('./spacetime'); var _ = spacetime.lazy(); var natural = _(function(n) //memoized automatically { return n; // Natural numbers is defined as the `n`th number becomes `n` }); var natural10 = _(natural) .take(10) .compute(function(x) {

Combine allMatch, noneMatch and anyMatch on a single stream

*爱你&永不变心* 提交于 2019-12-05 13:08:24
I would like to have the following logic: (i know it doesn't work because it consumes the stream more than once). but i am not sure how to achieve it. Stream<ByteBuffer> buffers = super.getBuffers().stream(); if (buffers.allMatch(b -> b.position() > 0)) { return OutgoingMessageStatus.FULLY_SENT; } else if (buffers.noneMatch(b -> b.position() > 0)) { return OutgoingMessageStatus.WAS_NOT_SENT; } else { return OutgoingMessageStatus.PARTIALLY_SENT; } How can I do that? Since the result of super.getBuffers() is List<ByteBuffer> , you can iterate over it twice. List<ByteBuffer> buffers = super

Java 8 Stream - Find largest nested list

若如初见. 提交于 2019-12-05 13:04:25
I have a Collection<List<SomeObject>> values How can I find the collection with the largest list using Streams? I have tried something like this, but it doesn't quite work values.stream().max(e -> e.stream().max(List::size).get()).get() But I get compilation error. Any ideas? I think you want values.stream().max(Comparator.comparingInt(List::size)).get() If you need duplicates, the best solution I can think of would be something like values.stream() .collect(Collector.of( ArrayList::new, (List<List<SomeObject>> best, List<SomeObject> elem) -> { if (best.isEmpty()) { best.add(elem); } else if

Throw RuntimeException inside Stream with Optional.orElseThrow

喜夏-厌秋 提交于 2019-12-05 12:57:24
问题 The following code works fine: Stream.of("key1", "key2") .map(key -> { SomeObject foo = service.find(key); if (foo == null) { throw new RuntimeException("No entity found with key: " + key); } return foo; }) // ... However, when I use orElseThrow from Optional: Stream.of("key1", "key2") .map(key -> Optional.ofNullable(someService.find(key)) .orElseThrow(() -> new RuntimeException("No entity found with key: " + key))) // ... I get a compile time error: Error:(129, 33) java: unreported exception