turn range of arraylist into string array - java

I have an arraylist with the size 0 or .. any size. And I want to turn anything inside into string list. So, suppose the arraylist has the size of 10 and I only want the first 5 elements of it. Instead of doing a for loop, any other efficient method?
Thanks.

You could use the subList method:
List<String> s = new ArrayList<>(Arrays.asList("one","two","three","four"));
List<String> sub = s.subList(0,2); //["one","two"]

Something like this, maybe?
List<Integer> intList = Arrays.asList(1, 2, 3, 5, 6, 7, 8, 9);
List<String> stringList = intList.stream().map(i -> i.toString())
.limit(5).collect(Collectors.toList());
System.out.println(stringList);
I'm not sure whether I understood your question correctly, but this way, you can turn anything into a list of strings first and limit it thereafter.

Related

How to merge arrays in alternating pattern without duplicates

I'm currently learning in school but am unable to complete this part of the assignment.
An explanation with the use of for loops would be greatly appreciated.
The numbers should be added to the merged array in an alternating pattern: first from list 1, then from list 2, then list 1 again, etc. If a number in one of the arrays already appears in the merged array, then it should be ignored, and the program should alternate to the other list again. For example, if the first list begins 1 2 3 10, and the second begins 3 4 5 8, then the merged list would begin 1 3 2 4 5 10 8.
Because the number of elements in the merged array is unknown, its size should be set to the maximum possible number of elements it should contain, and after all elements which should form the merged array appear, any remaining unfilled spaces in the array should be 0. The first 0 encountered in the array should signal the end of the “actual” elements of the array, and therefore the 0s at the end of the array should not be printed by your program.
I propose to use a HashSet to remember which number you have already inserted into the array. For each number, you first check if the hash set already contains the number; if not, you add it to both the array and the set. For large inputs, this is much faster than checking the result array for each number. O(n*log(n)) or so (depending on how well the HashSet works for your input) instead of O(n^2).
#bubble
An example using a Set is very simple - however your teacher is asking for
an alternate list:
Integer[] one = new Integer[] {10,2,3,1};
Integer[] two = new Integer[] {3,8,5,4};
List<Integer> li_one = Arrays.asList(one); // First convert the arrays to a list
List<Integer> li_two = Arrays.asList(two);
Set<Integer> set = new HashSet<>();
set.addAll(li_one);
set.addAll(li_two);
System.out.println("The unique list is: " + set);
A HashSet was my first idea too, but the order of storing values depends
one hash values. The ... teacher likes to have alternating values which
I dont like to comment - because it is a really strange request.
Following code prints: merged list is: [1, 3, 2, 4, 5, 10, 8]
int[] one = new int[] {1,2,3,10};
int[] two = new int[] {3,4,5,8};
int one_len = one.length;
int two_len = two.length;
List<Integer> merged = new ArrayList<>();
int oneval,twoval;
for (int i = 0;i < one_len;i++)
{
oneval = one[i];
if (!merged.contains(oneval)) merged.add(oneval);
if (i < two_len)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
if (two_len > one_len)
{
for (int i = one_len; i < two_len;i++)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
System .out.println("merged list is: " + merged);

Java - Create an IntStream with a given range, then randomise each element using a map function

So I've created an IntStream where I give it a range of 1 - 9. I would like to be able to use the map function to take each element in the given range (1-9) and randomise each one.
Essentially I would like to stream the numbers 1 - 9 in a different order each time the program is ran. (I'm open to other ideas, but it has to be using streams).
I've heard about using Java's Random class but i'm not sure how i would implement that over a map of each element.
I've tried doing this but there are errors:
IntStream.range(1, 9).map(x -> x = new Random()).forEach(x -> System.out.println(x));
Any help would be appreciated.
It can be done this way too using Random.ints:
new Random().ints(1,10)
.distinct()
.limit(9)
.forEach(System.out::println);
Output:
9 8 4 2 6 3 5 7 1
EDIT
If you need a Stream with the values then do this:
Stream<Integer> randomInts = new Random().ints(1, 10)
.distinct()
.limit(9)
.boxed();
If you need a List with the values then do this:
List<Integer> randomInts = new Random().ints(1, 10)
.distinct()
.limit(9)
.boxed()
.collect(Collectors.toList());
Streams are really not suitable for this job. Like, really really.
A better way is to use Collections.shuffle:
// you can replace this with however you want to populate your array.
// You can do a for loop that loops from 1 to 9 and add each number.
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
Collections.shuffle(list);
// now "list" is in a random order
EDIT:
Now that I know you have a custom list, here's another approach. Write two methods that converts your custom list to a normal ArrayList and the other way round as well. Convert your custom list to an ArrayList, do the shuffle, and convert it back.
Just for fun, Stream, when paralleled, can kind of produce stuff in a random order, but not really.
I ran this code for 10 times:
IntStream.range(1, 10).parallel().forEach(System.out::print);
And here were the output:
347195628
342179856
832497165
328194657
326479581
341287956
873629145
837429156
652378914
632814579
public static void main(String[] args) {
Random random = new Random();
//infinite stream of integers between 1(inclusive) and 10(exclusive)
IntStream intStream = random.ints(1, 10);
//from the infinite stream get a stream of 9 random and distinct integers and print them
intStream.distinct().limit(9).forEach(System.out::println);
}

Loop through assigned values in an array

Say I have given array
int[] array = new int[50];
Then, say I assign 5 numbers to 5 locations
array[4] = 2
array[12] = 0
array[17] = 5
array[42] = 8
array[49] = 4
Is there a way I can loop through just the numbers I assigned without having a list that says "4, 12, 17, 42, 49" and get the output of "2, 0, 5, 8, 4"?
You can use the boxed type Integer which can be null.
Integer[] array = new Integer[50];
... assignment ...
for (Integer i : array)
if (i != null)
System.out.println(i);
Is there a way I can loop through just the numbers I assigned without having a list that says "4, 12, 17, 42, 49" and get the output of "2, 0, 5, 8, 4"?
No. you cannot do this with arrays. This will break the very purpose of array. You are actually expecting it to behave like a map.
Use proper map for this purpose. Here is an example
HashMap<Integer, Integer> map = new HashMap<>();
map.put(4, 2);
map.put(12, 0);
for(Integer value : map.values()) {
System.out.println(value);
}
Yes and no.
No, because you have to iterate over the whole array, unless you somehow store what values are set (what you don't want).
Yes, you can achieve to only get the output you want by setting some default values. For example initialize the array with Integer.MIN_VALUE and only handle values that are not equal to that value.

permute/scramble arraylist elements in java

suppose I have arraylist of integers...is there a way that I can generate a random permutation/arrangement of the elements in the arraylist
so if the list is {1,2,3,4,5,6}
calling some method randomPermute() would change it to something random like
{1,3,2,6,5,4}
Collections.shuffle() does the job:
public static void shuffle(List<?> list) -
Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.
http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)
For example
ArrayList<Integer>anArrayList = new ArrayList<Integer>();
anArrayList.add(1);
anArrayList.add(2);
anArrayList.add(3);
anArrayList.add(4);
anArrayList.add(5);
System.out.println(anArrayList);
Collections.shuffle(anArrayList);
System.out.println(anArrayList);
Sample Output
[1, 2, 3, 4, 5]
[3, 5, 1, 2, 4]
You can use the Knuth shuffle: go through the positions 1 through n−1, and for each position i swap the element currently there with an arbitrarily chosen element from positions i through n, inclusive.
Edit: The answer by hooch is better. :)
A simple example:
ArrayList<MyObject> myObjects = new ArrayList<MyObject>();
//code -- load myObjects...
Collections.shuffle(myObjects);

Is the Braces in the following statement means an open array?

Integer[] ints = list.toArray(new Integer[]{});
If I remove "{}" the compiler asks to fill in a dimension for the array. What do the two braces mean as a command?
It means you initialize the array with what is in between the braces. Ex:
new Integer[] { 1, 2, 3}
Makes an array with 1, 2 and 3. On the other hand:
new Integer[] {}
Just mean that you initialize an array without any values. So it is the same as new Integer[0].
This actually means empty array. The {} allow you to supply the elements of the array:
Integer[] ints = list.toArray(new Integer[]{1, 2, 3});
is equivalent to:
Integer[] ints = new Integer[3];
ints[0] = 1;
ints[1] = 2;
ints[2] = 3;
Check this link:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
for more information - go to Creating, Initializing, and Accessing an Array section.
Yes, an empty array. Just like Integer[0].

Categories