I'm trying to convert some python code to java and need to setup a default value of a list. I know the default value, the size of the list and my goal is to setup a default value and then later in my program change them. In python I simply do this(to create 10 items with a value of zero):
list = [0]*10
I am trying to do:
List<Integer> list1 = Arrays.asList(0*10); // it just multiples 0 by 10.
It doest work, I know I can do something like this:
for(int i = 0;i<10;i++)
{
list1.add(0);
}
I was wondering if there was an better way(instead of the for loop)?
Arrays.fill lets you avoid the loop.
Integer[] integers = new Integer[10];
Arrays.fill(integers, 0);
List<Integer> integerList = Arrays.asList(integers);
Collections.nCopies is your friend if you need a list instead of an array:
List<Integer> list = Collections.nCopies(10, 0);
If a mutable list is needed, wrap it:
List<Integer> list = new ArrayList<>(Collections.nCopies(10, 0));
Maybe you just need an array?
int[] array = new int[10];
You need a list if you need to change the size of it dynamically. If you don't need this feature, an array may suit your needs, and it will automatically initialize all the values to 0 for you.
You can try:
List<Integer> list1 = Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
There are 10 zeroes. You need to know the number of elements at the compile time, but you have only one line. If you don't know the number of elements at compile time, then you can use the suggested Arrays.fill() approach.
There's nothing built into the standard libraries, as far as I'm aware. But you can easily write such a method once and call it from wherever you want. For example:
public static <T> List<T> newArrayList(T value, int size) {
List<T> list = new ArrayList<T>(size);
for (int i = 0; i < size; i++) {
list.add(value);
}
return list;
}
If you never want to change the size of the list (i.e. add or remove elements), Mike Samuel's answer is probably more efficient. Also note that if you're using a mutable type, you may not get what you want:
List<StringBuilder> list = newArrayList(new StringBuilder(), 10);
list.get(0).append("Foo");
System.out.println(list.get(5)); // Prints "Foo"
... as each element in the list will be a reference to the same object.
If you are using java 8 or above you can do the following. Here are the required imports:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
Here is the code to get it to work
List<Integer> integers = new ArrayList() {{
IntStream.range(0,5).forEach((i) -> add(0));
}};
The double braces are not a mistake they are required! I hope this helps.
List<Integer> list1 = IntStream.range(0, 10)
.mapToObj(i -> 0)
.collect(Collectors.toList());
In Java, not really. Java is relatively verbose when it comes to this sort of stuff, so there isn't much you can do that is simple, other than a loop like you have.
I would stick with the for loop.
BTW... 0*10 = 0 so just enter in the amount you need instead
ArrayList<Integer> list = new ArrayList<Integer>(10);
Related
What is the equvalent of Pyhton arr[1:] in Java and C#, like how to get all elements before and after the defined one?
for example in Python I have
input:
arr=[1,6,7,9]
print(arr[1:])
output:
6,7,9
WITHOUT FOR, WHILE, IF
preferably for ArrayList
In java:-
1 - create a list and add elements.
2 - use subList(start_index, end index) method.
// Internally its use for loop to create a new copy of arraylist with defined index. but its faster as there are many system methods involved in this process. which work on os level
3 - store result in list and print it.
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(3);
a.add(4);
a.add(5);
a.add(6);
System.out.println(a);
List<Integer> b = a.subList(1, a.size());
System.out.println(b);
In C# -
1 - use array.skip(no of element you want to skip).
2 - store output in array.
C# is not my primary language so if there is anything wrong please comment I will correct it.
In C-sharp:
Use Linq methods to take the first n elements or skip the first n elements.
firstArray = array.Take(14).ToArray(); // take only the first 14 elements
secondArray = array.Skip(2).ToArray(); // skip the first two elements
You could also combine those Linq commands like this:
Array = array.Skip(4).Take(10).ToArray(); // takes the subarray from 4-14
In Java:
Use Stream methods like in https://www.boraji.com/java-8-stream-limit-and-skip-methods-example
List<Integer> numbers = new ArrayList<>(1, 2, 3, 4);
numbers.stream().limit(3).forEach(nn -> {
System.out.println(n);
});
numbers.stream().skip(2).forEach(nn -> {
System.out.println(n);
});
Or alternatively:
List<String> arrlist = arrlist.subList(2, arrlist.size()); // index from to
You can define a method:
int[] cut(int[] a, int start, int end);
which accepts array a, start and end indexes, and returns copy of array a from start to end indexes.
Alternative for Python arr[1:] in Java may be cut(arr, 1, arr.length);
In Java:
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
List<String> sublist = list.subList(list.indexOf("b"), list.size());
System.out.println(sublist);
}
}
I am breaking my mind to find a solution to the following problem.
I have 4 different ArrayList that get their values from a Database.
They can have size from 0 (including) till what ever.
Each list may have different size and values also.
What I am trying to do effectively is :
Compare all the non 0 size lists and check if they have some common integers and what are those values.
Any ideas?
Thank you!
If you need a collection of common integers for all, excluding empty ones:
List<List<Integer>> lists = ...
Collection<Integer> common = new HashSet<Integer>(lists.get(0));
for (int i = 1; i < lists.size(); i++) {
if (!lists.get(i).isEmpty())
common.retainAll(lists.get(i));
}
at the end the common will contain integers that common for all of them.
You can use set intersection operations with your ArrayList objects.
Something like this:
List<Integer> l1 = new ArrayList<Integer>();
l1.add(1);
l1.add(2);
l1.add(3);
List<Integer> l2= new ArrayList<Integer>();
l2.add(4);
l2.add(2);
l2.add(3);
List<Integer> l3 = new ArrayList<Integer>(l2);
l3.retainAll(l1);
Now, l3 should have only common elements between l1 and l2.
You might be wanting to use apache commons CollectionUtils.intersection() to get the intersection of two collections...
Iteratively generate the intersection, and if it is not empty when you are done - you have a common element, and it is in this resulting collection.
Regarding empty lists: just check if its size() is 0, and if it is - skip this list.
You can do this. If you have multiple elements to search, put the search in a loop.
List aList = new ArrayList();
aList.add(new Integer(1));
if(aList !=null && !aList.isEmpty()) {
if(aList.contains(1)) {
System.out.println("got it");
}
}
I have two arrayLists and I am trying to "subtract" one arrayList from another. For example, if I have one arrayList [1,2,3] and I am trying to subtract [0, 2, 4] the resulting arrayList should be [1,3].
List<Integer> a = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Integer> b = Arrays.asList(0, 2, 4);
subtract(a,b) // should return [1,3]
Here is my code.
//returns a new IntSet after subtracting a from b
// .minus().toString()
ArrayList<Integer> minusArray = new ArrayList<Integer>();
minusArray.addAll(array1);
for(int i =0; i< minusArray.size(); i++){
for(int j = 0; j < array2.size(); j++){
if(minusArray.get(i).equals(array2.get(j))){
minusArray.remove(i);
if(i == 0){
;
}
else if(j == 0){
;
}
else{
i = 0;
j = 0;
}
}
else{}
}
}
return minusArray;
My code works in some cases, like if arrayList1 = [4,6] and arrayList2 = [6] it will will give me a result of [4]. But if I try something like [1,2,4] and [0,4,8]
I get this exception:
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at IntSet.minus(IntSet.java:119)
at IntSetDriver.main(IntSetDriver.java:62)
Here is the code I have come up with. I have done test runs through it and to me I think it should work. The user inputs these arrayLists and they are presorted, I also do not know Hash or big-O.
ArrayList<Integer> minusArray = new ArrayList<Integer>();
minusArray.addAll(array1);
for(int i =0; i< minusArray.size(); i++){
for(int j = 0; j < array2.size(); j++){
if(minusArray.get(i).equals(array2.get(j))){
minusArray.remove(i);
}
else{}
}
}
return minusArray;
Is there some reason you can't simply use List.removeAll(List)?
List<Integer> one = new ArrayList<Integer>();
one.add(1);
one.add(2);
one.add(3);
List<Integer> two = new ArrayList<Integer>();
two.add(0);
two.add(2);
two.add(4);
one.removeAll(two);
System.out.println(one);
result: "[1, 3]"
Try to use subtract method of org.apache.commons.collections.CollectionUtils class.
Returns a new Collection containing a - b. The cardinality of each element e in the returned Collection will be the cardinality of e in a minus the cardinality of e in b, or zero, whichever is greater.
CollectionUtils.subtract(java.util.Collection a, java.util.Collection b)
From Apache Commons Collections
Java 8
You can also use streams:
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(1, 2, 4, 5);
List<Integer> diff = list1.stream()
.filter(e -> !list2.contains(e))
.collect (Collectors.toList()); // (3)
This answer does not manipulate the original list. If intention is to modify the original list then we can use remove. Also we can use forEach (default method in Iterator) or stream with filter.
Using ListUtils
Another option is to use ListUtils if we are using Apache common:
ListUtils.subtract(list, list2)
This subtracts all elements in the second list from the first list, placing the results in a new list. This differs from List.removeAll(Collection) in that cardinality is respected; if list1 contains two occurrences of null and list2 only contains one occurrence, then the returned list will still contain one occurrence.
Traversing the minusArray using an index is one way to do this, but I suggest you make use of the contains(Object) method, which will allow you then to use remove(Object) for the particular element of array2.
Of course, there's always the removeAll(Collection) which does pretty much everything you need...
You can use org.apache.commons.collections.ListUtils and make all that you want in only one line =)
List resultList = ListUtils.subtract(list, list2);
Your problem is that in your minusArray.remove(...) call you may shrink the size of the minusArray. To fix this, start at array.size() - 1 and count backwards to 0
Check that - even that won't fix it. You need to reverse the order of your loops
I'm guessing you get the range problem because you've eliminated one of the elements which changes what the inner loop is looking for (I know this problem occurs when dealing with normal Lists and Collections).
What I've had to do in the past to work around this, is to create a list of items that need to be removed (that is ones that are found in the original list). Iterate through that new list and directly eliminate the original list's elements without having to have an iterator moving through it.
Try this answer if removeAll() is not what you want. e.g. if you are interested in something like Calculating difference of two lists with duplicates
subtract(a,b)
b.forEach((i)->a.remove(i));
a now contains
[1, 3]
This follows the suggestion of Guava implementors on how to implement subtract
"create an ArrayList containing a and then call remove on it for each element in b."
Which behaves like this implementation used in Apache commons
Difference to removeAll()
[1,2,2,3].removeAll([1,2,3]) //is empty
[1,2,3].forEach((i)->[1,2,2,3].remove(i)); //a is [2]
My parameterized solution would be like:
<T> ArrayList<T> subtract(ArrayList<T> alpha, ArrayList<T> beta) {
ArrayList<T> gamma = new ArrayList<T>();
alpha.forEach(n -> {if (!beta.contains(n)) gamma.add(n); });
return gamma;
}
I am trying to "combine" two arrayLists, producing a new arrayList that contains all the numbers in the two combined arrayLists, but without any duplicate elements and they should be in order. I came up with this code below. I run through it and it makes sense to me, but Im not sure if I can be using < or > to compare get(i)'s in arrayLists. I am adding all the elements in array1 into the plusArray. Then I am going through the plusArray and comparing it to array2 to see if any of array2's elements exist inside plusArray. If they do I am doing nothing, but if they dont then I am trying to add it in its correct position. Perhaps my nested for loops being used incorrectly? Note: The ArrayLists are presorted by the user in increasing order.
ArrayList<Integer> plusArray = new ArrayList<Integer>();
for(int i = 0; i < array1.size(); i++){
plusArray.add(array1.get(i));
}
for(int i = 0; i < plusArray.size(); i++){
for(int j = 0; j < array2.size(); j++){
if(array2.get(j) < plusArray.get(i)){
plusArray.add(i,array2.get(j));
}
else if(plusArray.get(i).equals(array2.get(j))){
;
}
else if(array2.get(j) > plusArray.get(i)){
plusArray.add(i, array2.get(j));
}
}
UPDATE: I dont get the exception below anymore. Instead it seems the program runs forever. I changed the location of where to add the elements in the < and > conditions.
///
Here is the exception that I get when my array lists are:
IntSet 1: { 1 2 }
IntSet 2: { 1 3 4 }
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at IntSet.plus(IntSet.java:92)
at IntSetDriver.main(IntSetDriver.java:61)
Firstly remove duplicates:
arrayList1.removeAll(arrayList2);
Then merge two arrayList:
arrayList1.addAll(arrayList2);
Lastly, sort your arrayList if you wish:
collections.sort(arrayList1);
In case you don't want to make any changes on the existing list, first create their backup lists:
arrayList1Backup = new ArrayList(arrayList1);
Instead of the code you wrote, you may use ArrayList.addAll() to merge the lists, Collections.sort() to sort it and finally traverse of the resulting ArrayList to remove duplicates. The aggregate complexity is thus O(n)+O(n*log(n))+O(n) which is equivalent to O(n*log(n)).
List<String> listA = new ArrayList<String>();
listA.add("A");
listA.add("B");
List<String> listB = new ArrayList<String>();
listB.add("B");
listB.add("C");
Set<String> newSet = new HashSet<String>(listA);
newSet.addAll(listB);
List<String> newList = new ArrayList<String>(newSet);
System.out.println("New List :"+newList);
is giving you
New List :[A, B, C]
Add ArrayList1, ArrayList2 and produce a Single arraylist ArrayList3.
Now convert it into
Set Unique_set = new HashSet(Arraylist3);
in the unique set you will get the unique elements.
Note
ArrayList allows to duplicate values.
Set doesn't allow the values to duplicate.
Hope your problem solves.
Java 8 Stream API can be used for the purpose,
ArrayList<String> list1 = new ArrayList<>();
list1.add("A");
list1.add("B");
list1.add("A");
list1.add("D");
list1.add("G");
ArrayList<String> list2 = new ArrayList<>();
list2.add("B");
list2.add("D");
list2.add("E");
list2.add("G");
List<String> noDup = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
noDup.forEach(System.out::println);
En passant, it shouldn't be forgetten that distinct() makes use of hashCode().
Here is one solution using java 8:
Stream.of(list1, list2)
.flatMap(Collection::stream)
.distinct()
// .sorted() uncomment if you want sorted list
.collect(Collectors.toList());
Perhaps my nested for loops being used incorrectly?
Hint: nested loops won't work for this problem. A simple for loop won't work either.
You need to visualize the problem.
Write two ordered lists on a piece of paper, and using two fingers to point the elements of the respective lists, step through them as you do the merge in your head. Then translate your mental decision process into an algorithm and then code.
The optimal solution makes a single pass through the two lists.
Add elements in first arraylist
ArrayList<String> firstArrayList = new ArrayList<String>();
firstArrayList.add("A");
firstArrayList.add("B");
firstArrayList.add("C");
firstArrayList.add("D");
firstArrayList.add("E");
Add elements in second arraylist
ArrayList<String> secondArrayList = new ArrayList<String>();
secondArrayList.add("B");
secondArrayList.add("D");
secondArrayList.add("F");
secondArrayList.add("G");
Add first arraylist's elements in second arraylist
secondArrayList.addAll(firstArrayList);
Assign new combine arraylist and add all elements from both arraylists
ArrayList<String> comboArrayList = new ArrayList<String>(firstArrayList);
comboArrayList.addAll(secondArrayList);
Assign new Set for remove duplicate entries from arraylist
Set<String> setList = new LinkedHashSet<String>(comboArrayList);
comboArrayList.clear();
comboArrayList.addAll(setList);
Sorting arraylist
Collections.sort(comboArrayList);
Output
A
B
C
D
E
F
G
Your second for loop should have j++ instead of i++
I'm not sure why your current code is failing (what is the Exception you get?), but I would like to point out this approach performs O(N-squared). Consider pre-sorting your input arrays (if they are not defined to be pre-sorted) and merging the sorted arrays:
http://www.algolist.net/Algorithms/Merge/Sorted_arrays
Sorting is generally O(N logN) and the merge is O(m+n).
your nested for loop
for(int j = 0; j < array2.size(); i++){
is infinite as j will always equal to zero, on the other hand, i will be increased at will in this loop. You get OutOfBoundaryException when i is larger than plusArray.size()
You don't have to handcode this. The problem definition is precisely the behavior of Apache Commons CollectionUtils#collate. It's also overloaded for different sort orders and allowing duplicates.
**Add elements in Final arraylist,**
**This will Help you sure**
import java.util.ArrayList;
import java.util.List;
public class NonDuplicateList {
public static void main(String[] args) {
List<String> l1 = new ArrayList<String>();
l1.add("1");l1.add("2");l1.add("3");l1.add("4");l1.add("5");l1.add("6");
List<String> l2 = new ArrayList<String>();
l2.add("1");l2.add("7");l2.add("8");l2.add("9");l2.add("10");l2.add("3");
List<String> l3 = new ArrayList<String>();
l3.addAll(l1);
l3.addAll(l2);
for (int i = 0; i < l3.size(); i++) {
for (int j=i+1; j < l3.size(); j++) {
if(l3.get(i) == l3.get(j)) {
l3.remove(j);
}
}
}
System.out.println(l3);
}
}
Output : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I got your point that you don't wanna use the built-in functions for merging or remove duplicates from the ArrayList.
Your first code is running forever because the outer for loop condition is 'Always True'.
Since you are adding elements to plusArray, so the size of the plusArray is increasing with every addition and hence 'i' is always less than it. As a result the condition never fails and the program runs forever.
Tip: Try to first merge the list and then from the merged list remove the duplicate elements. :)
I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}