Converting String of digits to List of integer [duplicate] - java

This question already has answers here:
How do I convert a Java 8 IntStream to a List?
(5 answers)
Closed 7 years ago.
I am doing some hands on exercise on java 8 stream features so thought of applying the knowledge with the problem Converting String of digits to List of integer
a typical test would look like
#Test
public void testGetListofIntegersFromString(){
List<Integer> result = getIntegers("123456780");
assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,0),result);
}
I have written below method
List<Integer> getIntegers(String value) {
return IntStream.rangeClosed(0, value.length() - 1).map(i -> Integer.valueOf(value.substring(i,i+1))).collect(?????);
}
I am stuck about which function to use to get The List Of Integers
I tried collect(Collectors.toList()) Its giving compilation error.
Please suggest if we can follow different to solve this .

Use String.chars():
"123456780".chars().map(c -> c-'0').boxed().collect(Collectors.toList());

Related

Combining orElseThrows? [duplicate]

This question already has answers here:
Use Java 8 Optional in existing Java 7 code
(4 answers)
Flattening a list of elements in Java 8 Optional pipeline
(2 answers)
Java 8 Optional and flatMap - what is wrong?
(1 answer)
What is the difference between Optional.flatMap and Optional.map?
(8 answers)
Closed 2 years ago.
I have the following code and it works as expected:
Optional.ofNullable(testItem.getId())
.map(testItemRepository::get)
.orElseThrow(() -> new TestException(ReturnCode.UNKNOWN_ID))
.orElseThrow(() -> new TestException(ReturnCode.UNKNOWN_ID));
I would like to know if there is a way to just have one orElseThrow-Part or do it less redundant ?
Use Optional#flatMap method that flattens the Optional structure as long the call of the method testItemRepositoryget results in Optional.
Optional.ofNullable(testItem.getId())
.flatMap(testItemRepository::get)
.orElseThrow(() -> new TestException(ReturnCode.UNKNOWN_ID));
I.e. from Optional<Optional<MyObject>> to Optional<MyObect>.
It seems to be the case that testItemRepository::get returns another Optional<Something>. In that case, you should not use map. Using map will get you a nested optional - Optional<Optional<Something>>, which as you have found out, is not nice to work with. flatMap is made for exactly this situation:
Optional.ofNullable(testItem.getId())
.flatMap(testItemRepository::get)
.orElseThrow(() -> new TestException(ReturnCode.UNKNOWN_ID));
flatMap turns an Optional<A> to an Optional<B>, given a Function<A, Optional<B>>.

transform List using lambda expressions [duplicate]

This question already has answers here:
How can I turn a List of Lists into a List in Java 8?
(12 answers)
Closed 2 years ago.
I have created a function to transform the elements of a list:
private List<Hostel> build(List<Hotel> hotels) {
return hotels.stream().map(h -> convert(h)).collect(toList());
}
but I have a compilation error:
required type: List<Hostel>
Provided: List<List<Hostel>>
From your error it seems convert(h) return a List<Hostel>, for that when you use a map, and collect the result is List<List<Hostel>>, to get List<Hostel>, you have to use flatMap instead of map, like this:
.flatMap(h -> convert(h).stream())

Sum a list of objects based on BigDecimal field in single line [duplicate]

This question already has answers here:
Adding up BigDecimals using Streams
(5 answers)
Closed 3 years ago.
Suppose we have:
class Foo {
public BigDecimal field;
}
and that we have a list of Foo instances, i.e. List<Foo> list.
How can we calculate the sum of the values of the field from the objects in the list in a single line?
I found examples of similar cases using streams but they handle simpler cases and do not work for this; such as calculating for List<Integer> or when the field is something easily "summable" (int, Integer...).
list.stream().map(foo -> foo.field).reduce(BigDecimal.ZERO, (a, b) -> a.add(b));

Merge each element of multiple lists into one Element and return another list in java 8 [duplicate]

This question already has answers here:
Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)
(14 answers)
Closed 5 years ago.
for simplicity I have 2 lists of String and I need to join the strings into one and create another list.
For eg --
List 1 = [a,b,c,d]
List 2 = [e,f,g,h]
I want the output as
List3 = [ae,bf,cg,dh]
I can do this using regular for loops. but dont know how to proceed for java8
I am trying to get myself thinking in n Java 8 :-)
I'm not sure there's a better (easy) way to do this than to access the elements from the two lists by index:
List<String> zipped = IntStream.range(0, list.size())
.mapToObj(i -> list1.get(i) + list2.get(i))
.collect(Collectors.toList());

Best way to sum an integer list [duplicate]

This question already has answers here:
Is there possibility of sum of ArrayList without looping
(13 answers)
Closed 6 years ago.
I was wondering what the best way to sum the elements of an integer list in java is.
I'm aware I could perform this with a for loop but I was expecting there might be inbuilt ways to do this, such as the reduce function in other languages.
The relevant code for this problem has been provided below.
public static int sumList(List<Integer> list) {
return 0; //should return sum of integers in list
}
You can use the Stream API in Java 8
return list.stream().mapToInt(i -> i).sum();
The .mapToInt(i -> i) is required as Java doesn't know how to sum any object but it does know how to sum an IntStream and this converts the Stream<Integer> into an IntStream

Categories