Reputation: 3250
I have old Java Code like below:
String str1 = "aaa,bbb,ccc,ddd,eee,fff,ggg";
String str2 = "111,222,333,444,555,666,777";
//Start
String[] str1Array = str1.split(",", -1);
String[] str2Array = str2.split(",", -1);
HashMap<String, String> someMap = new HashMap<String, String>();
if (str1Array.length == str2Array.length) {
for (int i = 0; i < str1Array.length; i++) {
if (str1Array[i].equalsIgnoreCase("bbb") || str1Array[i].equalsIgnoreCase("ddd") || str1Array[i].equalsIgnoreCase("ggg")) {
System.out.println("Processing:" + str1Array[i] + "-" + str2Array[i]);
someMap.put(str1Array[i], str2Array[i]);
}
}
}
for (Map.Entry<String, String> entry : someMap.entrySet()) {
System.out.println(someProcessMethod1(entry.getKey()) + " : " + someProcessMethod2(entry.getValue()));
}
//Finish
I am trying to use Java 8 (I am still learning), and trying to filter and process the filtered values. Need some pointers here.
I am starting here (I know its wrong):
String[] mixAndFilter = (String[]) Stream.concat(Stream.of(str1Array), Stream.of(str2Array)).filter(???????).thenWhatHere()
.toArray(b -> new String[b]);
for (String b : mixAndFilter) {
System.out.println(mapkey : mapValue);
}
What should I do here to filter those three strings and use them in my someProcessMethods
as its done the old way? If possible, is there a way to get thing done from Start
to Finish
in Java 8 way? Any pointers/solution/pseudo-code is welcome.
Update (as asked by WJS):
The goal is to:
Filter bbb, ddd, ggg
strings from first array and then map those with the respective values in second array. so that the expected output is:
bbb : 222
ddd : 444
ggg : 777
Upvotes: 0
Views: 1053
Reputation: 40034
The easiest way to use streams is to:
i
is contained in the set, pass that index thru the filter.String str1 = "aaa,bbb,ccc,ddd,eee,fff,ggg";
String str2 = "111,222,333,444,555,666,777";
Set<String> filterList = Set.of("bbb", "ddd", "ggg");
String[] str1Array = str1.split(",", -1);
String[] str2Array = str2.split(",", -1);
Map<String, String> someMap = IntStream
.range(0, str1Array.length).boxed()
.filter(i -> filterList.contains(str1Array[i]))
.collect(Collectors.toMap(i -> str1Array[i],
i -> str2Array[i]));
someMap.entrySet().forEach(System.out::println);
prints
bbb=222
ddd=444
ggg=777
It is possible to make the splitting of the strings as part of the streaming process. But I found it much more cumbersome to do.
Upvotes: 2