From
val array = intArrayOf(5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4)
I need to convert to ArrayList<Int>
I have tried array.toTypedArray()
But it converted to Array<Int> instead
You can use toCollection function and specify ArrayList as a mutable collection to fill:
val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
You can get List<Int> with a simple toList call like so:
val list = intArrayOf(5, 3, 0, 2).toList()
However if you really need ArrayList you can create it too:
val list = arrayListOf(*intArrayOf(5, 3, 0, 2).toTypedArray())
or using more idiomatic Kotlin API as suggested by #Ilya:
val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
Or if you'd like to do the above yourself and save some allocations:
val arrayList = intArrayOf(5, 3, 0, 2).let { intList ->
ArrayList<Int>(intList.size).apply { intList.forEach { add(it) } }
}
Related
I am writing a myset class that has a Array of Object. I am trying override the toString method but it is not printing the elements when I call testing.
here is the method override
#Override
public String toString()
{
if(size==0){
return "[]";
}else{
string result="["+ arr[0];
for(int i=1;i<size;i++)
{
result+=", "+arr[i];
}
}
result+="]";
return result;
}
this is the array I am Trying to call
private static Object[] arr={1, 2, 3, 4 ,5, 6, 'A', 8 , "easha", 0, 44};
System.out.print(arr);
this is how I am calling it in the main
this is the result I get
[Ljava.lang.Object;#1dbd16a6%
FYI: I have a size method that calculates the size.
I was expecting the array to look like this {1, 2, 3, 4 ,5, 6, 'A', 8 , "easha", 0, 44}
but the result is this [Ljava.lang.Object;#1dbd16a6% `
I have a MutableList with generic with Int, like MutableList.
I wonder how to use kotlin call java method remove(int position) and remove(Integer object) correctly?
public void remove(int position) {
if (this.list != null && this.list.size() > position) {
this.list.remove(position);
notifyDataSetChanged();
}
}
public void remove(T t) {
if (t != null && this.list != null && !this.list.isEmpty()) {
boolean removed = false;
try {
removed = this.list.remove(t);
} catch (Exception e) {
e.printStackTrace();
}
if (removed) {
notifyDataSetChanged();
}
}
}
There are overall 4 methods for removing items in kotlin.collections.MutableList as of Kotlin 1.2.30:
remove - used to remove element once. Calls to this method are compiled to calls to the Java method List.remove(Object o).
removeAt - used to remove at a certain position. Calls to this method are compiled to calls to the Java method List.remove(int index).
removeAll - used to remove a collection, each element multiple times
removeIf - remove using a predicate, each element multiple times
Below is an example of how you can use each method. In the comments you can find what each method would print to the console and a brief explanation of what it does:
fun main(args: Array<String>) {
val l: MutableList<Int> = mutableListOf<Int>(1, 2, 3, 3, 4, 5, 6, 7, 1, 1, 1)
println(l.remove(1)) // true
println(l) // [2, 3, 3, 4, 5, 6, 7, 1, 1, 1] - removes first element and stops
println(l.removeAt(0)) // 2 - removes exactly on a specific position
println(l) // [3, 3, 4, 5, 6, 7, 1, 1, 1]
try {
println(l.removeAt(10000))
} catch(e: IndexOutOfBoundsException) {
println(e) // java.lang.IndexOutOfBoundsException: Index: 10000, Size: 9
}
println(l.removeAll(listOf(3, 4, 5))) // true
println(l) // [6, 7, 1, 1, 1] - removes elements in list multiple times, 3 removed multiple times
println(l.removeIf { it == 1 }) // true
println(l) // [6, 7] - all ones removed
}
...
true
[2, 3, 3, 4, 5, 6, 7, 1, 1, 1]
2
[3, 3, 4, 5, 6, 7, 1, 1, 1]
java.lang.IndexOutOfBoundsException: Index: 10000, Size: 9
true
[6, 7, 1, 1, 1]
true
[6, 7]
Finally i find the answer in Kotlin doc by myself. Kotlin will box generics
int to Integer if you declare the variable as Int?, because only an Object can be null.You can use the tool in android studio which can show the kotlin bytecode to find out that.
If we call java method like the question image:
val a:Int = 0
remove(a) // will call java method remove(int position)
val a:Int? = 0
remove(a) // will call java method remove(T t) to remove object
the result is different! If have better choice, we should avoid use like that.
Seems that other answers just give alternatives of remove(int position) but they didn't answer the question directly (according to the edit).
So you can use this code:
val list = mutableListOf("ah!", "I", "died!")
(list as java.util.List<String>).remove(1)
println(list)
Result:
[ah!, died!]
That's it! You've successfully invoked remove(int position) from Java.
This will raise some warnings, just ignore them.
Try it online!
So I have a Arraylist. It is currently holding integers. I would like to get list of integers that are not in the arraylist from a certain range. For example if the range of numbers was from 1 to 5, if the arraylist contains 1,3,4 then the output should 2 and 5. The numbers stored in the ArrayList should also be unique hence I am thinking of using Hashset. This is my code so far:
HashSet<Integer> abc = new HashSet<>();
while(myrs.next()){
try {
//RoomIdsThatAreCurrentlyReserved.add(Integer.parseInt(myrs.getObject(1).toString()));
abc.add(Integer.parseInt(myrs.getObject(1).toString()));
} catch (SQLException e) {
e.printStackTrace();
My code is basically reading from a result set.
With Eclipse Collections, the following will work using MutableSet. Using MutableSet here since you seem to be open for using Set.
MutableSet<Integer> set = Sets.mutable.with(1, 2, 3, 4, 5);
MutableSet<Integer> anotherSet = Sets.mutable.with(2, 3, 4);
MutableSet<Integer> result = set.difference(anotherSet);
System.out.println(result); //[1, 5]
Note: I am a committer for Eclipse Collections.
Here is simple example :
Arraylist a={1,2,3,4,5};
Arraylist b={2,3,4};
if you won't an output like 1 and 5.
then
simply used this:
List<Integer> c = new ArrayList<>(a);
c.removeAll(b);
Why don't you do like this,
Iterator iterator = hashSet.iterator();
while (iterator.hasNext()){
int currentIteratorValue = (int) iterator.next();
if(currentIteratorValue != 1 && currentIteratorValue != 3 && currentIteratorValue != 4){
System.out.println(currentIteratorValue); //Prints 5 and 2
}
}
It's a 1-liner.
Given:
List<Integer> list; // populated elsewhere
// copy to a set if the list is large so it will perform better
Set<Integer> set = new HashSet<>(list);
Then:
List<Integer> missing = IntStream.range(a, b)
.filter(i -> !set.contains(i))
.collect(Collectors.toList());
If the list is small you can skip the set and just use
.filter(i -> !list.contains(i))
but that is O(n) whereas the set contains is O(1).
Using https://github.com/google/guava (java 1.6)
List<Integer> fullList = Lists.newArrayList(1, 2, 3, 4 , 5);
List<Integer> partOfList = Lists.newArrayList(1, 3, 4 );
FluentIterable<Integer> missing = FluentIterable.from(fullList).filter(Predicates.not(Predicates.in(partOfList)));
If I have a list with integers, is there a way to construct another list, where integers are summed if the difference to the head of the new list is below a threashold? I would like to solve this using Java 8 streams. It should work similar to the Scan operator of RxJava.
Example: 5, 2, 2, 5, 13
Threashold: 2
Result: 5, 9, 13
Intermediate results:
5
5, 2
5, 4 (2 and 2 summed)
5, 9 (4 and 5 summed)
5, 9, 13
Sequential Stream solution may look like this:
List<Integer> result = Stream.of(5, 2, 2, 5, 13).collect(ArrayList::new, (list, n) -> {
if(!list.isEmpty() && Math.abs(list.get(list.size()-1)-n) < 2)
list.set(list.size()-1, list.get(list.size()-1)+n);
else
list.add(n);
}, (l1, l2) -> {throw new UnsupportedOperationException();});
System.out.println(result);
Though it looks not much better as good old solution:
List<Integer> input = Arrays.asList(5, 2, 2, 5, 13);
List<Integer> list = new ArrayList<>();
for(Integer n : input) {
if(!list.isEmpty() && Math.abs(list.get(list.size()-1)-n) < 2)
list.set(list.size()-1, list.get(list.size()-1)+n);
else
list.add(n);
}
System.out.println(list);
Seems that your problem is not associative, so it cannot be easily parallelized. For example, if you split the input into two groups like this (5, 2), (2, 5, 13), you cannot say whether the first two items of the second group should be merged until the first group is processed. Thus I cannot specify the proper combiner function.
As Tagir Valeev observed, (+1) the combining function is not associative, so reduce() won't work, and it's not possible to write a combiner function for a Collector. Instead, this combining function needs to be applied left-to-right, with the previous partial result being fed into the next operation. This is called a fold-left operation, and unfortunately Java streams don't have such an operation.
(Should they? Let me know.)
It's possible to sort-of write your own fold-left operation using forEachOrdered while capturing and mutating an object to hold partial state. First, let's extract the combining function into its own method:
// extracted from Tagir Valeev's answer
void combine(List<Integer> list, int n) {
if (!list.isEmpty() && Math.abs(list.get(list.size()-1)-n) < 2)
list.set(list.size()-1, list.get(list.size()-1)+n);
else
list.add(n);
}
Then, create the initial result list and call the combining function from within forEachOrdered:
List<Integer> result = new ArrayList<>();
IntStream.of(5, 2, 2, 5, 13)
.forEachOrdered(n -> combine(result, n));
This gives the desired result of
[5, 9, 13]
In principle this can be done on a parallel stream, but performance will probably degrade to sequential given the semantics of forEachOrdered. Also note that the forEachOrdered operations are performed one at a time, so we needn't worry about thread safety of the data we're mutating.
I know that the Stream's masters "Tagir Valeev" and "Stuart Marks" already pointed out that reduce() will not work because the combining function is not associative, and I'm risking a couple of downvotes here. Anyway:
What about if we force the stream to be sequential? Wouldn't we be able then to use reduce? Isn't the associativity property only needed when using parallelism?
Stream<Integer> s = Stream.of(5, 2, 2, 5, 13);
LinkedList<Integer> result = s.sequential().reduce(new LinkedList<Integer>(),
(list, el) -> {
if (list.isEmpty() || Math.abs(list.getLast() - el) >= 2) {
list.add(el);
} else {
list.set(list.size() - 1, list.getLast() + el);
}
return list;
}, (list1, list2) -> {
//don't really needed, as we are sequential
list1.addAll(list2); return list1;
});
Java 8 way is define custom IntSpliterator class:
static class IntThreasholdSpliterator extends Spliterators.AbstractIntSpliterator {
private PrimitiveIterator.OfInt it;
private int threashold;
private int sum;
public IntThreasholdSpliterator(int threashold, IntStream stream, long est) {
super(est, ORDERED );
this.it = stream.iterator();
this.threashold = threashold;
}
#Override
public boolean tryAdvance(IntConsumer action) {
if(!it.hasNext()){
return false;
}
int next = it.nextInt();
if(next<threashold){
sum += next;
}else {
action.accept(next + sum);
sum = 0;
}
return true;
}
}
public static void main( String[] args )
{
IntThreasholdSpliterator s = new IntThreasholdSpliterator(3, IntStream.of(5, 2, 2, 5, 13), 5);
List<Integer> rs= StreamSupport.intStream(s, false).mapToObj(Integer::valueOf).collect(toList());
System.out.println(rs);
}
Also you can hack it as
List<Integer> list = Arrays.asList(5, 2, 2, 5, 13);
int[] sum = {0};
list = list.stream().filter(s -> {
if(s<=2) sum[0]+=s;
return s>2;
}).map(s -> {
int rs = s + sum[0];
sum[0] = 0;
return rs;
}).collect(toList());
System.out.println(list);
But I am not sure that this hack is good idea for production code.
I need your help in arraylist problem. I have 2 arraylist.
ArrayList<string> a = {"fruit=apple,grape,banana;nut=pistachio,chestnut,walnut,peanut;vegetable=broccoli,carrot,cabbage,tomato"}
Arraylist<String> b = {"1:1:2 2:1:2 2:3:4 3:4:4"}
Ok, array b is represent the food in a. lets say
1:1:2 means apple:nut:carrot ,
2:1:2 means grape:pistachio:carrot,
2:3:4 means grape:walnut:tomato and
3:4:4 means banana:peanut:tomato.
Currently I have no idea at all. Hopefully you guys can help me about the idea how to do this.
Thanks in advance
Well, you currently have several problems which are probably confusing the situation:
There is no such class ArrayList<string>, I guess you mean List<string>
Currently your lists consist of a single element, which is a comma / space delimited string. You probably want something more like this:
List fruit = new List(new string[] {"apple", "grape", "banana" });
List nut = new List(new string[] {"pistachio", "chestnut", "walnut", "peanut" });
List vegetable = new List(new string[] {"broccoli", "carrot", "cabbage", "tomato" });
This gives you a list where each element is a nut, fruit or vegetable respectively.
Also your second list should probably look more like this:
List<int[]> combinations = new List<int[]>(
new int[][]
{
new int[] {1, 1, 2},
new int[] {2, 1, 2},
new int[] {2, 3, 4},
new int[] {3, 4, 4},
});
I.e. conbinations is a list of combinations, where each combination consists of 3 integers - the index of each element in the list. (This is possibly a tad confusing and by no means the only option - ask if this bit isn't clear).
In face as arrays are 0-indexed in c#, in fact you probably want this instead:
List<int[]> combinations = new List<int[]>(
new int[][]
{
new int[] {0, 0, 1},
new int[] {1, 0, 1},
new int[] {1, 2, 3},
new int[] {2, 3, 3},
});
This at least makes your data easier to work with, so the only questions remaining are:
How do you get from what you have to the above? (I'll let you have a go at that yourself).
What is it that you are trying to do?
Try Below code it works as expected let me know it it does not fulfill use case.
public static List<String> fruits = new ArrayList<String>();
public static List<String> nuts = new ArrayList<String>();
public static List<String> vegitables = new ArrayList<String>();
/**
* #param args
* #throws ParseException
* #author Rais.Alam
*/
public static void main(String[] args) throws ParseException
{
fruits.add("apple");
fruits.add("grape");
fruits.add("banana");
nuts.add("pistachio");
nuts.add("chestnut");
nuts.add("walnut");
nuts.add("peanut");
vegitables.add("broccoli");
vegitables.add("carrot");
vegitables.add("cabbage");
vegitables.add("tomato");
System.out.println(getValue("1:1:2"));
System.out.println(getValue("2:1:2"));
System.out.println(getValue("2:3:4"));
System.out.println(getValue("3:4:4"));
}
public static String getValue(String key)
{
String returnString = "";
String[] arr = key.split(":");
returnString += fruits.get(Integer.parseInt(arr[0]) - 1) == null ? "" : fruits.get(Integer.parseInt(arr[0]) - 1) + ":";
returnString += nuts.get(Integer.parseInt(arr[1]) - 1) == null ? "" : nuts.get(Integer.parseInt(arr[1]) - 1) + ":";
returnString += vegitables.get(Integer.parseInt(arr[2]) - 1) == null ? "" : vegitables.get(Integer.parseInt(arr[2]) - 1);
return returnString;
}
After running the program you will get below output
apple:pistachio:carrot
grape:pistachio:carrot
grape:walnut:tomato
banana:peanut:tomato