Reputation: 265
after reading about streams I am trying to use them now and already with simple examples the first questions arise. I would like to implement a very simple encryption algorithm, which uses substitution. There is some text to be encrypted:
static List<Integer> text = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
There is some password:
private List<Integer> password = Arrays.asList(1, 5, 7, 3);
The idea is now to add the password values to the text values. The result should be
1+1, 2+5, 3+7, 4+3, 5+1, 6+5, ...
So I have to create a stream from password, which starts from the beginning when reaching the end of the above list. This part I already managed to do.
Now I somehow have to merge 2 streams into 1 stream. Any ideas, how to accomplish that?
Upvotes: 1
Views: 290
Reputation: 328598
I would probably stream indexes here:
IntStream.range(0, text.size())
.map(i -> text.get(i) + password.get(i % password.size())
.toArray();
Upvotes: 5
Reputation: 316
These are lists your result will also be a list.
You you create a new List crypt = new ArrayList(); then you loop through the text list and for each item in the text list you add the value in the password list index that is the index in the text list % password.size();
List<Integer> crypt= new ArrayList<Integer>();
for(int index= 0;index=<text.size();index++){
crypt.add(text.get(index)+password.get(index % password.size());
}
Upvotes: 0