java-stream

Java 8/9: Can a character in a String be mapped to its indices (using streams)?

☆樱花仙子☆ 提交于 2019-12-03 09:57:42
Given a String s and a char c , I'm curious if there exists some method of producing a List<Integer> list from s (where the elements within list represent the indices of c within s ). A close, but incorrect approach would be: public static List<Integer> getIndexList(String s, char c) { return s.chars() .mapToObj(i -> (char) i) .filter(ch -> ch == c) .map(s::indexOf) // Will obviously return the first index every time. .collect(Collectors.toList()); } The following inputs should yield the following output: getIndexList("Hello world!", 'l') -> [2, 3, 9] Can be done with IntStream public static

Java 8 streams group by 3 fields and aggregate by sum and count produce single line output

僤鯓⒐⒋嵵緔 提交于 2019-12-03 09:49:45
I know there a similar questions asked in the forum but none of them seem to be addressing my problem fully. Now I'm very new to Java 8, so please bear with me. I have a list of Products, for example: Input: name category type cost prod1 cat2 t1 100.23 prod2 cat1 t2 50.23 prod1 cat1 t3 200.23 prod3 cat2 t1 150.23 prod1 cat2 t1 100.23 Output: Single line (name, category, type) summing the cost and count of products. Product { public String name; public String category; public String type; public int id; public double cost; } I need to group this by name, category and type and produce a single

How to make a Stream from a DirectoryStream

南楼画角 提交于 2019-12-03 09:49:11
When reading the API for DirectoryStream I miss a lot of functions. First of all it suggests using a for loop to go from stream to List . And I miss the fact that it a DirectoryStream is not a Stream . How can I make a Stream<Path> from a DirectoryStream in Java 8? DirectoryStream is not a Stream (it's been there since Java 7, before the streams api was introduced in Java 8) but it implements the Iterable<Path> interface so you could write: try (DirectoryStream<Path> ds = ...) { Stream<Path> s = StreamSupport.stream(ds.spliterator(), false); } While it is possible to convert a DirectoryStream

Join a list of object's properties into a String

ⅰ亾dé卋堺 提交于 2019-12-03 09:40:37
I'm learning lambda right now, and I wonder how can I write this code by a single line with lambda. I have a Person class which includes an ID and name fields Currently, I have a List<Person> which stores these Person objects. What I want to accomplish is to get a string consisting of person's id just like. "id1,id2,id3" . How can I accomplish this with lambda? To retrieve a String consisting of all the ID's separated by the delimiter "," you first have to map the Person ID's into a new stream which you can then apply Collectors.joining on. String result = personList.stream().map(Person::getId

How to use collect call in Java 8?

人走茶凉 提交于 2019-12-03 09:39:46
Lets say we have this boring piece of code that we all had to use: ArrayList<Long> ids = new ArrayList<Long>(); for (MyObj obj : myList){ ids.add(obj.getId()); } After switching to Java 8, my IDE is telling me that I can replace this code with collect call , and it auto-generates: ArrayList<Long> ids = myList.stream().map(MyObj::getId).collect(Collectors.toList()); However its giving me this error: collect(java.util.stream.Collector) in Steam cannot be applied to: (java.util.stream.Collector, capture, java.util.List>) I tried casting the parameter but its giving me undefined A and R , and the

Java8 Stream : Collect elements after a condition is met

我怕爱的太早我们不能终老 提交于 2019-12-03 09:29:09
My POJO is as follows class EventUser { private id; private userId; private eventId; } I retrieve EventUser object as follows: List<EventUser> eventUsers = eventUserRepository.findByUserId(userId); Say the 'eventUsers' is as follows: [ {"id":"id200","userId":"001","eventId":"1010"}, {"id":"id101","userId":"001","eventId":"4212"}, {"id":"id402","userId":"001","eventId":"1221"}, {"id":"id301","userId":"001","eventId":"2423"}, {"id":"id701","userId":"001","eventId":"5423"}, {"id":"id601","userId":"001","eventId":"7423"} ] Using streaming, and without using any intermediate variable , how can I

Java 8 stream operations execution order

我的梦境 提交于 2019-12-03 09:22:49
问题 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); List<Integer> twoEvenSquares = numbers.stream().filter(n -> { System.out.println("filtering " + n); return n % 2 == 0; }).map(n -> { System.out.println("mapping " + n); return n * n; }).limit(2).collect(Collectors.toList()); for(Integer i : twoEvenSquares) { System.out.println(i); } when executed the logic below output came filtering 1 filtering 2 mapping 2 filtering 3 filtering 4 mapping 4 4 16 if the stream follows the short

Java 8 Streams: How to call once the Collection.stream() method and retrieve an array of several aggregate values with different fields

半城伤御伤魂 提交于 2019-12-03 09:22:48
问题 I'm starting with the Stream API in Java 8. Here is my Person object I use: public class Person { private String firstName; private String lastName; private int age; private double height; private double weight; public Person(String firstName, String lastName, int age, double height, double weight) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.height = height; this.weight = weight; } public String getFirstName() { return firstName; } public String getLastName()

Why is Stream.sorted not type-safe in Java 8?

馋奶兔 提交于 2019-12-03 09:21:34
This is from the Stream interface from Oracle's implementation of JDK 8: public interface Stream<T> extends BaseStream<T, Stream<T>> { Stream<T> sorted(); } and it is very easy to blow this up at run time and no warning will be generated at compile time. Here is an example: class Foo { public static void main(String[] args) { Arrays.asList(new Foo(), new Foo()).stream().sorted().forEach(f -> {}); } } which will compile just fine but will throw an exception at run time: Exception in thread "main" java.lang.ClassCastException: Foo cannot be cast to java.lang.Comparable What could be the reason

Java 8 Stream - Filter and foreach method not printing as expected

匆匆过客 提交于 2019-12-03 09:16:23
I am executing the following program: Stream.of("d2", "a2", "b1", "b3", "c") .filter(s -> { System.out.println("filter: " + s); return true; }) .forEach(s -> System.out.println("forEach: " + s)); And the output I got is: filter: d2 forEach: d2 filter: a2 forEach: a2 filter: b1 forEach: b1 filter: b3 forEach: b3 filter: c forEach: c However, I was expecting the following output: filter: d2 filter: a2 filter: b1 filter: b3 filter: c forEach: d2 forEach: a2 forEach: b1 forEach: b3 forEach: c Meaning, first the filter method loop should have executed completely and then the forEach method loop