This question already has answers here:
How to create a map out of two arrays using streams in Java?
(3 answers)
Closed 1 year ago.
I have two Arrays as below:
k[] = {"K1","K2","K3"}
v[] = {"V1","V2","V3"}
I want to iterate these two arrays using Stream API in such a way so that I collect them as a Map as
[K1=V1,K2=V2,K3=V3]
Assuming both arrays have the same length, you could create a stream with the indexes. This can be done with IntStream.range(start,end) where the start is 0 and the end the size of your array. Because we use range, the end will not be included.
In this stream, you need to collect the result to a map, the key will be the value in first array with the given index, the value will be the value in the second array with the given index.
Do note that an IntStream is not the same as a Stream<Integer>. In this case, we will need a stream of Integers so that we can collect them in the Collector (Collector does not work with primitive types). To do this, call the method .boxed() to convert it to a Stream<Integer>
String k[] = {"K1", "K2", "K3"};
String v[] = {"V1", "V2", "V3"};
Map<String, String> result = IntStream.range(0, k.length).boxed().collect(Collectors.toMap(i -> k[i], i -> v[i]));
This gives the following result
{K1=V1, K2=V2, K3=V3}
IntStream.range(0, k.length).collect(Collectors.toMap(i -> k[i], i -> v[i]));
Related
This question already has answers here:
Find all indexes of a value in a List [duplicate]
(3 answers)
Closed 12 days ago.
I have a list of strings and I want to add to a set all indexes from array where the string is not empty,
I tried doing this:
columnNum.addAll((Collection<? extends Integer>) IntStream.range(0, row.size()).filter(i-> StringUtils.isNotEmpty(row.get(i))));
but I get an exception
You have to use boxed:
var list = List.of("","a","","b");
var set = IntStream.range(0, list.size())
.filter(i ->
!list.get(i).isEmpty()).boxed().collect(Collectors.toSet());
Collect the stream to a List first. An IntStream is not a Collection.
columnNum.addAll(IntStream.range(0, row.size())
.filter(i-> StringUtils.isNotEmpty(row.get(i)))
.boxed().collect(Collectors.toList())); // or .toList() with Java 16+
final Set<Integer> set1 = new HashSet<>();
final Set<Integer> set2 = new HashSet<>();
Stream.of(set1, set2).mapToInt(???).forEach(intValue -> code)
I have 2 Set of Integer and in a Stream but i want to map them all into Integers. I can't find a way to do it using maptoInt or flatMap so i can extract all Integers of both Sets.
You can use Stream.concat(set1.stream(), set2.stream()) which creates a new combined stream so you can then map your values to int
Aside from stream concatenation mentioned at https://stackoverflow.com/a/65675352 you can also use
Stream.of(set1, set2)
.flatMap(set -> set.stream())
.mapToInt(i -> i)
.forEach(System.out::println);
since flatMap expects mapping to Stream of values which should be "used" by current stream.
So in your case you want stream containing values inside each set which can be created via
set -> set.stream()
or Set::stream.
This question already has answers here:
Convert List of List into list in java
(5 answers)
Closed 5 years ago.
I have a multimap Map<T,List<L>> map and I need a list with all the values of the values from the map, namely List<L>. With map.values() I get a List<List<L>>, but thats not what I want.
Does someone know a clean solution without looping?
If you are using Java 8, you could collect all L values from all List<L>s in a single List<L> by Stream#flatMap:
final List<L> list = map
// get a Collection<List<L>>
.values()
// make a stream from the collection
.stream()
// turn each List<L> into a Stream<L> and merge these streams
.flatMap(List::stream)
// accumulate the result into a List
.collect(Collectors.toList());
Otherwise, a for-each approach with Collection#addAll can be applied:
final List<L> list = new ArrayList<>();
for (final List<L> values : map.values()) {
list.addAll(values);
}
This question already has answers here:
How do I keep the iteration order of a List when using Collections.toMap() on a stream?
(6 answers)
Closed 5 years ago.
I have the following hash map
Map<String,Double> map_1 = new LinkedHashMap<>();
with some keys: e.g. ["hello_1", "hello_2", "hello_3"].
Then, I iterate through these keys using stream API and saving new results in map2:
Map<String,Double> map_2 = new LinkedHashMap<>();
map_2 = map_1.keySet()
.stream()
.collect(
Collectors.toMap(entry -> entry,
entry -> {
Double value = map_1.get(entry);
return (value + 5);
}));
but the new hash map has keys in another order, despite it is defined as LinkedHashMap. I think the problem is during stream + collect steps.
Anyone could suggest me a solution?
Thanks
The order of the keys actually gets messed up in the collect step in this case.
You need to specify that you want to collect to a LinkedHashMap.
I have a map<String, Object> and an array of int[] which is supposed to contain the map keys.
Is there a nice and short way to convert the keys to int, without using a loop?
myArray = myMap.keySet().toArray(new int[5]);
I useJava 8.
Thanks!
Assuming all your String keys can be safely parsed as integers :
int[] keys = myMap.keySet().stream().mapToInt(Integer::parseInt).toArray();
keySet() returns a Set<String>.
stream() returns a Stream<String>.
mapToInt() maps that Stream<String> to an IntStream by applying Integer.parseInt() on each String.
toArray() returns an array of all the elements of the IntStream.
myMap.keySet().toArray(); // returns an array of keys
myMap.values().toArray(); // returns an array of values
Attention!
Should be noted that the ordering of both arrays may not be the same.