Intersection between two arraylist Java - java

I wanted to find an intersection between two arraylist that are of byte[] format and return the common indices. I have the code as follows and it works correctly:
ArrayList<Integer> intersect = new ArrayList<Integer>();
for(int j = 0; j < A.size(); j++)
{
byte [] t = A.get(j);
for (int j1 = 0; j1 < B.size(); j1++)
{
byte[] t1 = B.get(j1);
if (Arrays.equals(t, t1))
{
intersect.add(j);
break;
}
}
}
However, as you can see, I have to use two for loops. Is there any way I can do it without using any for loops? I have tried to use "retainAll" but for some reason, it kept giving me an empty array. What can be the possible reason for that?

If you just dont want to use for loops, you may try the Java 8 streams, since you have not shared the complete code I did not try it out.
List<T> intersect = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());

I think for T your solution with brutforce is not so bad. This is a small refactoring of it. Yes, for specific T (e.g. int) you could use special structures, but in general case, I think this is not implementable.
public static <T> List<Integer> intersect(List<T> A, List<T> B, BiPredicate<T, T> isEqual) {
List<Integer> intersect = new LinkedList<>();
int i = -1;
for (T a : A) {
i++;
if (B.stream().anyMatch(b -> isEqual.test(a, b)))
intersect.add(i);
}
return intersect;
}
Client code could look like:
List<byte[]> a = Collections.emptyList();
List<byte[]> b = Collections.emptyList();
List<Integer> intersect = intersect(a, b, Arrays::equals);

This may help:
public <T> List<T> intersection(List<T> list1, List<T> list2) {
List<T> list = new ArrayList<T>();
for (T t : list1) {
if(list2.contains(t)) {
list.add(t);
}
}
return list;
}
Reference:
Intersection and union of ArrayLists in Java

Related

How can I sort a list based on another list values in Java [duplicate]

I've seen several other questions similiar to this one but I haven't really been able to find anything that resolves my problem.
My use case is this: user has a list of items initially (listA). They reorder the items and want to persist that order (listB), however, due to restrictions I'm unable persist the order on the backend so I have to sort listA after I retrieve it.
So basically, I have 2 ArrayLists (listA and listB). One with the specific order the lists should be in (listB) and the other has the list of items (listA). I want to sort listA based on listB.
Using Java 8:
Collections.sort(listToSort,
Comparator.comparing(item -> listWithOrder.indexOf(item)));
or better:
listToSort.sort(Comparator.comparingInt(listWithOrder::indexOf));
Collections.sort(listB, new Comparator<Item>() {
public int compare(Item left, Item right) {
return Integer.compare(listA.indexOf(left), listA.indexOf(right));
}
});
This is quite inefficient, though, and you should probably create a Map<Item, Integer> from listA to lookup the positions of the items faster.
Guava has a ready-to-use comparator for doing that: Ordering.explicit()
Let's say you have a listB list that defines the order in which you want to sort listA. This is just an example, but it demonstrates an order that is defined by a list, and not the natural order of the datatype:
List<String> listB = Arrays.asList("Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday");
Now, let's say that listA needs to be sorted according to this ordering. It's a List<Item>, and Item has a public String getWeekday() method.
Create a Map<String, Integer> that maps the values of everything in listB to something that can be sorted easily, such as the index, i.e. "Sunday" => 0, ..., "Saturday" => 6. This will provide a quick and easy lookup.
Map<String, Integer> weekdayOrder = new HashMap<String, Integer>();
for (int i = 0; i < listB.size(); i++)
{
String weekday = listB.get(i);
weekdayOrder.put(weekday, i);
}
Then you can create your custom Comparator<Item> that uses the Map to create an order:
public class ItemWeekdayComparator implements Comparator<Item>
{
private Map<String, Integer> sortOrder;
public ItemWeekdayComparator(Map<String, Integer> sortOrder)
{
this.sortOrder = sortOrder;
}
#Override
public int compare(Item i1, Item i2)
{
Integer weekdayPos1 = sortOrder.get(i1.getWeekday());
if (weekdayPos1 == null)
{
throw new IllegalArgumentException("Bad weekday encountered: " +
i1.getWeekday());
}
Integer weekdayPos2 = sortOrder.get(i2.getWeekday());
if (weekdayPos2 == null)
{
throw new IllegalArgumentException("Bad weekday encountered: " +
i2.getWeekday());
}
return weekdayPos1.compareTo(weekdayPos2);
}
}
Then you can sort listA using your custom Comparator.
Collections.sort(listA, new ItemWeekdayComparator(weekdayOrder));
Speed improvement on JB Nizet's answer (from the suggestion he made himself). With this method:
Sorting a 1000 items list 100 times improves speed 10 times on my
unit tests.
Sorting a 10000 items list 100 times improves speed 140 times (265 ms for the whole batch instead of 37 seconds) on my
unit tests.
This method will also work when both lists are not identical:
/**
* Sorts list objectsToOrder based on the order of orderedObjects.
*
* Make sure these objects have good equals() and hashCode() methods or
* that they reference the same objects.
*/
public static void sortList(List<?> objectsToOrder, List<?> orderedObjects) {
HashMap<Object, Integer> indexMap = new HashMap<>();
int index = 0;
for (Object object : orderedObjects) {
indexMap.put(object, index);
index++;
}
Collections.sort(objectsToOrder, new Comparator<Object>() {
public int compare(Object left, Object right) {
Integer leftIndex = indexMap.get(left);
Integer rightIndex = indexMap.get(right);
if (leftIndex == null) {
return -1;
}
if (rightIndex == null) {
return 1;
}
return Integer.compare(leftIndex, rightIndex);
}
});
}
Problem : sorting a list of Pojo on the basis of one of the field's all possible values present in another list.
Take a look at this solution, may be this is what you are trying to achieve:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Employee> listToSort = new ArrayList<>();
listToSort.add(new Employee("a", "age11"));
listToSort.add(new Employee("c", "age33"));
listToSort.add(new Employee("b", "age22"));
listToSort.add(new Employee("a", "age111"));
listToSort.add(new Employee("c", "age3"));
listToSort.add(new Employee("b", "age2"));
listToSort.add(new Employee("a", "age1"));
List<String> listWithOrder = new ArrayList<>();
listWithOrder.add("a");
listWithOrder.add("b");
listWithOrder.add("c");
Collections.sort(listToSort, Comparator.comparing(item ->
listWithOrder.indexOf(item.getName())));
System.out.println(listToSort);
}
}
class Employee {
String name;
String age;
public Employee(String name, String age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
#Override
public String toString() {
return "[name=" + name + ", age=" + age + "]";
}
}
O U T P U T
[[name=a, age=age11], [name=a, age=age111], [name=a, age=age1], [name=b, age=age22], [name=b, age=age2], [name=c, age=age33], [name=c, age=age3]]
Here is a solution that increases the time complexity by 2n, but accomplishes what you want. It also doesn't care if the List R you want to sort contains Comparable elements so long as the other List L you use to sort them by is uniformly Comparable.
public class HeavyPair<L extends Comparable<L>, R> implements Comparable<HeavyPair<L, ?>> {
public final L left;
public final R right;
public HeavyPair(L left, R right) {
this.left = left;
this.right = right;
}
public compareTo(HeavyPair<L, ?> o) {
return this.left.compareTo(o.left);
}
public static <L extends Comparable<L>, R> List<R> sort(List<L> weights, List<R> toSort) {
assert(weights.size() == toSort.size());
List<R> output = new ArrayList<>(toSort.size());
List<HeavyPair<L, R>> workHorse = new ArrayList<>(toSort.size());
for(int i = 0; i < toSort.size(); i++) {
workHorse.add(new HeavyPair(weights.get(i), toSort.get(i)))
}
Collections.sort(workHorse);
for(int i = 0; i < workHorse.size(); i++) {
output.add(workHorse.get(i).right);
}
return output;
}
}
Excuse any terrible practices I used while writing this code, though. I was in a rush.
Just call HeavyPair.sort(listB, listA);
Edit: Fixed this line return this.left.compareTo(o.left);. Now it actually works.
Here is an example of how to sort a list and then make the changes in another list according to the changes exactly made to first array list. This trick will never fails and ensures the mapping between the items in list. The size of both list must be same to use this trick.
ArrayList<String> listA = new ArrayList<String>();
ArrayList<String> listB = new ArrayList<String>();
int j = 0;
// list of returns of the compare method which will be used to manipulate
// the another comparator according to the sorting of previous listA
ArrayList<Integer> sortingMethodReturns = new ArrayList<Integer>();
public void addItemstoLists() {
listA.add("Value of Z");
listA.add("Value of C");
listA.add("Value of F");
listA.add("Value of A");
listA.add("Value of Y");
listB.add("this is the value of Z");
listB.add("this is the value off C");
listB.add("this is the value off F");
listB.add("this is the value off A");
listB.add("this is the value off Y");
Collections.sort(listA, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
// TODO Auto-generated method stub
int returning = lhs.compareTo(rhs);
sortingMethodReturns.add(returning);
return returning;
}
});
// now sort the list B according to the changes made with the order of
// items in listA
Collections.sort(listB, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
// TODO Auto-generated method stub
// comparator method will sort the second list also according to
// the changes made with list a
int returning = sortingMethodReturns.get(j);
j++;
return returning;
}
});
}
try this for java 8:
listB.sort((left, right) -> Integer.compare(list.indexOf(left), list.indexOf(right)));
or
listB.sort(Comparator.comparingInt(item -> list.indexOf(item)));
import java.util.Comparator;
import java.util.List;
public class ListComparator implements Comparator<String> {
private final List<String> orderedList;
private boolean appendFirst;
public ListComparator(List<String> orderedList, boolean appendFirst) {
this.orderedList = orderedList;
this.appendFirst = appendFirst;
}
#Override
public int compare(String o1, String o2) {
if (orderedList.contains(o1) && orderedList.contains(o2))
return orderedList.indexOf(o1) - orderedList.indexOf(o2);
else if (orderedList.contains(o1))
return (appendFirst) ? 1 : -1;
else if (orderedList.contains(o2))
return (appendFirst) ? -1 : 1;
return 0;
}
}
You can use this generic comparator to sort list based on the the other list.
For example, when appendFirst is false below will be the output.
Ordered list: [a, b]
Un-ordered List: [d, a, b, c, e]
Output:
[a, b, d, c, e]
One way of doing this is looping through listB and adding the items to a temporary list if listA contains them:
List<?> tempList = new ArrayList<?>();
for(Object o : listB) {
if(listA.contains(o)) {
tempList.add(o);
}
}
listA.removeAll(listB);
tempList.addAll(listA);
return tempList;
Not completely clear what you want, but if this is the situation:
A:[c,b,a]
B:[2,1,0]
And you want to load them both and then produce:
C:[a,b,c]
Then maybe this?
List c = new ArrayList(b.size());
for(int i=0;i<b.size();i++) {
c.set(b.get(i),a.get(i));
}
that requires an extra copy, but I think to to it in place is a lot less efficient, and all kinds of not clear:
for(int i=0;i<b.size();i++){
int from = b.get(i);
if(from == i) continue;
T tmp = a.get(i);
a.set(i,a.get(from));
a.set(from,tmp);
b.set(b.lastIndexOf(i),from);
}
Note I didn't test either, maybe got a sign flipped.
Another solution that may work depending on your setting is not storing instances in listB but instead indices from listA. This could be done by wrapping listA inside a custom sorted list like so:
public static class SortedDependingList<E> extends AbstractList<E> implements List<E>{
private final List<E> dependingList;
private final List<Integer> indices;
public SortedDependingList(List<E> dependingList) {
super();
this.dependingList = dependingList;
indices = new ArrayList<>();
}
#Override
public boolean add(E e) {
int index = dependingList.indexOf(e);
if (index != -1) {
return addSorted(index);
}
return false;
}
/**
* Adds to this list the element of the depending list at the given
* original index.
* #param index The index of the element to add.
*
*/
public boolean addByIndex(int index){
if (index < 0 || index >= this.dependingList.size()) {
throw new IllegalArgumentException();
}
return addSorted(index);
}
/**
* Returns true if this list contains the element at the
* index of the depending list.
*/
public boolean containsIndex(int index){
int i = Collections.binarySearch(indices, index);
return i >= 0;
}
private boolean addSorted(int index){
int insertIndex = Collections.binarySearch(indices, index);
if (insertIndex < 0){
insertIndex = -insertIndex-1;
this.indices.add(insertIndex, index);
return true;
}
return false;
}
#Override
public E get(int index) {
return dependingList.get(indices.get(index));
}
#Override
public int size() {
return indices.size();
}
}
Then you can use this custom list as follows:
public static void main(String[] args) {
class SomeClass{
int index;
public SomeClass(int index) {
super();
this.index = index;
}
#Override
public String toString() {
return ""+index;
}
}
List<SomeClass> listA = new ArrayList<>();
for (int i = 0; i < 100; i++) {
listA.add(new SomeClass(i));
}
SortedDependingList<SomeClass> listB = new SortedDependingList<>(listA);
Random rand = new Random();
// add elements by index:
for (int i = 0; i < 5; i++) {
int index = rand.nextInt(listA.size());
listB.addByIndex(index);
}
System.out.println(listB);
// add elements by identity:
for (int i = 0; i < 5; i++) {
int index = rand.nextInt(listA.size());
SomeClass o = listA.get(index);
listB.add(o);
}
System.out.println(listB);
}
Of course, this custom list will only be valid as long as the elements in the original list do not change. If changes are possible, you would need to somehow listen for changes to the original list and update the indices inside the custom list.
Note also, that the SortedDependingList does currently not allow to add an element from listA a second time - in this respect it actually works like a set of elements from listA because this is usually what you want in such a setting.
The preferred way to add something to SortedDependingList is by already knowing the index of an element and adding it by calling sortedList.addByIndex(index);
If the two lists are guaranteed to contain the same elements, just in a different order, you can use List<T> listA = new ArrayList<>(listB) and this will be O(n) time complexity. Otherwise, I see a lot of answers here using Collections.sort(), however there is an alternative method which is guaranteed O(2n) runtime, which should theoretically be faster than sort's worst time complexity of O(nlog(n)), at the cost of 2n storage
Set<T> validItems = new HashSet<>(listB);
listA.clear();
listB.forEach(item -> {
if(validItems.contains(item)) {
listA.add(item);
}
});
List<String> listA;
Comparator<B> comparator = Comparator.comparing(e -> listA.indexOf(e.getValue()));
//call your comparator inside your list to be sorted
listB.stream().sorted(comparator)..
Like Tim Herold wrote, if the object references should be the same, you can just copy listB to listA, either:
listA = new ArrayList(listB);
Or this if you don't want to change the List that listA refers to:
listA.clear();
listA.addAll(listB);
If the references are not the same but there is some equivalence relationship between objects in listA and listB, you could sort listA using a custom Comparator that finds the object in listB and uses its index in listB as the sort key. The naive implementation that brute force searches listB would not be the best performance-wise, but would be functionally sufficient.
IMO, you need to persist something else. May be not the full listB, but something. May be just the indexes of the items that the user changed.
Try this. The code below is general purpose for a scenario where listA is a list of Objects since you did not indicate a particular type.
Object[] orderedArray = new Object[listA.size()];
for(int index = 0; index < listB.size(); index ++){
int position = listB.get(index); //this may have to be cast as an int
orderedArray[position] = listA.get(index);
}
//if you receive UnsupportedOperationException when running listA.clear()
//you should replace the line with listA = new List<Object>()
//using your actual implementation of the List interface
listA.clear();
listA.addAll(orderedArray);
Just encountered the same problem.
I have a list of ordered keys, and I need to order the objects in a list according to the order of the keys.
My lists are long enough to make the solutions with time complexity of N^2 unusable.
My solution:
<K, T> List<T> sortByOrder(List<K> orderedKeys, List<T> objectsToOrder, Function<T, K> keyExtractor) {
AtomicInteger ind = new AtomicInteger(0);
Map<K, Integer> keyToIndex = orderedKeys.stream().collect(Collectors.toMap(k -> k, k -> ind.getAndIncrement(), (oldK, newK) -> oldK));
SortedMap<Integer, T> indexToObj = new TreeMap<>();
objectsToOrder.forEach(obj -> indexToObj.put(keyToIndex.get(keyExtractor.apply(obj)), obj));
return new ArrayList<>(indexToObj.values());
}
The time complexity is O(N * Log(N)).
The solution assumes that all the objects in the list to sort have distinct keys. If not then just replace SortedMap<Integer, T> indexToObj by SortedMap<Integer, List<T>> indexToObjList.
To avoid having a very inefficient look up, you should index the items in listB and then sort listA based on it.
Map<Item, Integer> index = IntStream.range(0, listB.size()).boxed()
.collect(Collectors.toMap(listB::get, x -> x));
listA.sort((e1, e2) -> Integer.compare(index.get(c1), index.get(c2));
So for me the requirement was to sort originalList with orderedList. originalList always contains all element from orderedList, but not vice versa. No new elements.
fun <T> List<T>.sort(orderedList: List<T>): List<T> {
return if (size == orderedList.size) {
orderedList
} else {
var keepIndexCount = 0
mapIndexed { index, item ->
if (orderedList.contains(item)) {
orderedList[index - keepIndexCount]
} else {
keepIndexCount++
item
}
}
}}
P.S. my case was that I have list that user can sort by drag and drop, but some items might be filtered out, so we preserve hidden items position.
If you want to do it manually. Solution based on bubble sort (same length required):
public void sortAbasedOnB(String[] listA, double[] listB) {
for (int i = 0; i < listB.length - 1; i++) {
for (int j = listB.length - 1; j > i; j--) {
if (listB[j] < listB[j - 1]){
double tempD = listB[j - 1];
listB[j - 1] = listB[j];
listB[j] = tempD;
String tempS = listA[j - 1];
listA[j - 1] = listA[j];
listA[j] = tempS;
}
}
}
}
If the object references should be the same, you can initialize listA new.
listA = new ArrayList(listB)
In Java there are set of classes which can be useful to sort lists or arrays. Most of the following examples will use lists but the same concept can be applied for arrays. A example will show this.
We can use this by creating a list of Integers and sort these using the Collections.sort(). The Collections (Java Doc) class (part of the Java Collection Framework) provides a list of static methods which we can use when working with collections such as list, set and the like. So in a nutshell, we can sort a list by simply calling: java.util.Collections.sort(the list) as shown in the following example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class example {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<Integer>();
ints.add(4);
ints.add(3);
ints.add(7);
ints.add(5);
Collections.sort(ints);
System.out.println(ints);
}
}
The above class creates a list of four integers and, using the collection sort method, sorts this list (in one line of code) without us having to worry about the sorting algorithm.

How to make java function take a list of objects of any class

I'm trying to write a Java function which takes a List of Lists holding objects of any class, and then calculates the size of the set consisting of all different combinations of inner list objects, where all objects come from different lists. The algorithm is simple:
int combos(List<List<Object>> inList) {
int res = 1;
for(List<Object> list : inList) {
res *= list.size();
}
return res;
}
But I'm getting this error when trying to run the function with a List<List<Integer>> object as input parameter:
List<List<Integer>> input = new ArrayList<List<Integer>>();
input.add(new ArrayList<Integer>());
input.get(0).add(1);
input.get(0).add(2);
combos(input);
The error:
The method combos(List<List<Object>>) in the type SpellChecker is not applicable for the arguments (List<List<Integer>>)
As far as I understand, Object is the parent class of Integer. So why doesn't this work? How can I make it work?
The relationship between Object and Integer does not apply to List<Object> and List<Integer>, see e.g. this related question for more details.
Use a type parameter:
<T> int combos(List<List<T>> inList) {
int res = 1;
for(List<T> list : inList) {
res *= list.size();
}
return res;
}
One solution is to use a type parameter in combos:
<T> int combos(List<List<T>> inList) {
int res = 1;
for(List<T> list : inList) {
res *= list.size();
}
return res;
}
This is closely related to this question about nested generics. The answer in that question provides some good info.
On top of the two good answers you already got here is another option.
public static void main(String[] args) {
List<List<Integer>> input = new ArrayList<>();
input.add(new ArrayList<>());
input.get(0).add(1);
input.get(0).add(2);
combos(input);
}
static int combos(List<? extends List<?>> inList) {
int res = 1;
for (List<?> list : inList) {
res *= list.size();
}
return res;
}
This also works, if you don't need to specialize the List Datatype as List<Integer>
List<List<Object>> input = new ArrayList<List<Object>>();
input.add( new ArrayList<Object>() );
input.get( 0 ).add( new Integer(1) );
input.get( 0 ).add( new Integer(2) );
combos( input );

iterate through ArrayList<T> java?

I'm learning Android and Java i have created a class let's say like this
class x(){
public int a;
public string b;
}
and then i initiate a list of this class and then added values to its properties like this
public ArrayList<x> GetList(){
List<x> myList = new ArrayList<x>();
x myObject = new x();
myObject.a = 1;
myObject.b = "val1";
mylist.add(x);
y myObject = new y();
myObject.a = 2;
myObject.b = "val2";
mylist.add(y);
return myList;
}
My Question is how can i loop through what GetList() return
i have tried
ArrayList<x> list = GetList();
Iterator<x> iterator = list.iterator();
but i don't know if this is the right way of doing this, plus i don't know what to do next i have added a breakpoint on the Iterator but it seemed to be null , the list have values thought
There are two ways to do this:
A for loop
Using the iterator method.
for loop:
for(x currentX : GetList()) {
// Do something with the value
}
This is what's called a "for-each" loop, and it's probably the most common/preferred method of doing this. The syntax is:
for(ObjectType variableName : InCollection)
You could also use a standard for loop:
ArrayList<x> list = GetList();
for(int i=0; i<list.size(); i++) {
x currentX = list.get(i);
// Do something with the value
}
The syntax for this is:
for(someStartingValue; doSomethingWithStartingValue; conditionToStopLooping)
iterator method:
Iterator<x> iterator = GetList().iterator();
while(iterator.hasNext()) {
x currentX = iterator.next();
// Do something with the value
}
You can loop through your array with a for-each loop:
for (x item: GetList()) {
doSomethingWithEachValue(item);
}
I guess you can iterate through the arraylist a number of ways. One way is the iterator:-
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
System.out.print("Original contents of al: ");
Iterator<String> itr = al.iterator();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
Another way would be a loop:
for(int i = 0; i < list.size(); i++){
list[i].a = 29;
}
Hope this helps in any way.
Ref
http://www.tutorialspoint.com/java/java_using_iterator.htm
http://examples.javacodegeeks.com/core-java/util/arraylist/arraylist-in-java-example-how-to-use-arraylist/
UPDATE
I thought that I should just put this out there from research due to the comment below about performance.
The Android docs
http://developer.android.com/training/articles/perf-tips.html
states:
The enhanced for loop (also sometimes known as "for-each" loop) can be used for collections >that implement the Iterable interface and for arrays. With collections, an iterator is >allocated to make interface calls to hasNext() and next(). With an ArrayList, a hand-written >counted loop is about 3x faster (with or without JIT), but for other collections the enhanced >for loop syntax will be exactly equivalent to explicit iterator usage.
There are several alternatives for iterating through an array:
static class Foo {
int mSplat;
}
Foo[] mArray = ...
public void zero() {
int sum = 0;
for (int i = 0; i < mArray.length; ++i) {
sum += mArray[i].mSplat;
}
}
public void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i < len; ++i) {
sum += localArray[i].mSplat;
}
}
public void two() {
int sum = 0;
for (Foo a : mArray) {
sum += a.mSplat;
}
}
zero() is slowest, because the JIT can't yet optimize away the cost of getting the array length once for every iteration through the
loop.
one() is faster. It pulls everything out into local variables,
avoiding the lookups. Only the array length offers a performance
benefit.
two() is fastest for devices without a JIT, and indistinguishable
from one() for devices with a JIT. It uses the enhanced for loop
syntax introduced in version 1.5 of the Java programming language.
So, you should use the enhanced for loop by default, but consider a hand-written counted loop for performance-critical ArrayList iteration. Also this is stated by Josh Bloch's Effective Java, item 46. The iterator and the index variables are both just clutter. Furthermore, they represent opportunities for error.
The preferred idiom for iterating over collections and arrays
for(Element e : elements){
doSomething(e);
}
Josh also states when you see the colon : read it as "In". The loop reads as for each element e in elements. I do not claim this work as my own even though I wish it was. If you want to learn more about efficient code then I suggest reading Josh Bloch's Effective Java.
Try the following:
class x {
public int a;
public String b;
}
private void test() {
List<x> items = getList();
for (x item: items) {
System.out.print("val: " + item.a);
}
}
private List<x> getList() {
List<x> items = new ArrayList<x>();
x oneObject = new x();
oneObject.a = 1;
oneObject.b = "val1";
items.add(oneObject);
x anotherObject = new x();
anotherObject.a = 2;
anotherObject.b = "val2";
items.add(anotherObject);
return items;
}

Java array object initialization

I just want ask, is it possible to initiliaze more objects with same constructor in one command?
Example of code:
Tile[] tiles = new Tile(5,5)[20];
Thanks for response.
Impossible as far as I know.
The code Tile[] tiles = new Tile[20]; just creates an array of references. To fill the array, you should create a Tile object and then assign the reference to one index of the array, such as:
tiles[0] = new Tile(5,5);
If all elements of the array pointing to the same object is OK, you can full fill the array simply use:
Tile tiles = new Tile[20];
Arrays.fill(tiles, new Tile(5,5));
No, you have to use a loop.
Tile[] tiles = new Tile[20];
for(int i = 0; i < tiles.length; i++) {
tiles[i] = new Tile(5, 5);
}
However, it is nice that in Java 8 we will be able to shorten this using the new Supplier class and a helper method.
static <E> E[] fill(E[] arr, Supplier<? extends E> supp) {
for(int i = 0; i < arr.length; i++) {
arr[i] = supp.get();
}
return arr;
}
We can then do the following:
Tile[] tiles = fill(new Tile[20], () -> new Tile(5, 5));
I think that's sort of nifty.
There's also a couple ways to do this without Java 8 by using reflection. Here's a way you can do it if the class has a copy constructor (a constructor that takes an object of its own class as an argument):
static <E> E[] duplicate(E[] arr, E element) {
#SuppressWarnings("unchecked")
Class<? extends E> cls = (Class<? extends E>)element.getClass();
try {
Constructor<? extends E> ctor = cls.getConstructor(cls);
for(int i = 0; i < arr.length; i++) {
arr[i] = ctor.newInstance(element);
}
} catch(Exception e) {
e.printStackTrace(System.err);
}
return arr;
}
So for example:
String[] arr = fill(new String[5], "Hello world!");
Reflection is a bit more unstable than the lambda, especially when dealing with subtypes and primitives. The lambda is great.
First, it is even not possible to initialize an object array with non-null value in one line (ok, except using {...} or filling them with same reference but I think it is not what you want)
You gotta create instance of array first, and fill individual element in the array:
e.g.
Foo[] myArray =new Foo[10];
for (int i = 0; i < myArray.length; ++i) {
myArray = new Foo();
}
If you are just looking for shorter code that you don't want to write the loop again and again, here is one option for you:
write a little util like this:
public class ArrayUtil {
public static T[] fillArray(T[] array, ArrayElementFactory elementFactory) {
for (int i = 0; i< array.length; ++i) {
array[i] = elementFactory.create(i);
}
return array;
}
}
public interface ArrayElementFactory<T> {
T create(int i);
}
The way to use is something like
Foo[] fooArray = fillArray(new Foo[10], new ArrayElementFactory<Foo>() {
Foo create(int i) { return new Foo(10,10); }};
If you are using Java8, I believe (haven't tried) you can use lambda expression which give you something like
Foo[] fooArray = fillArray(new Foo[10], i -> new Foo(10,10));

How to Iterate through two ArrayLists Simultaneously? [duplicate]

This question already has answers here:
How to most elegantly iterate through parallel collections?
(8 answers)
Closed 6 years ago.
I Have Two Array Lists, Declared as:
ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
Both of the these fields contain exactly, the Same No of Values, which are infact corresponding in Nature.
I know I can iterate over one of the loops like this:
for(JRadioButton button: category)
{
if(button.isSelected())
{
buttonName = button.getName();
System.out.println(buttonName);
}
}
But, I would like to iterate over both the LISTS simultaneously. I know they have the exact same size. How do I Do that?
You can use Collection#iterator:
Iterator<JRadioButton> it1 = category.iterator();
Iterator<Integer> it2 = cats_ids.iterator();
while (it1.hasNext() && it2.hasNext()) {
...
}
java8 style:
private static <T1, T2> void iterateSimultaneously(Iterable<T1> c1, Iterable<T2> c2, BiConsumer<T1, T2> consumer) {
Iterator<T1> i1 = c1.iterator();
Iterator<T2> i2 = c2.iterator();
while (i1.hasNext() && i2.hasNext()) {
consumer.accept(i1.next(), i2.next());
}
}
//
iterateSimultaneously(category, cay_id, (JRadioButton b, Integer i) -> {
// do stuff...
});
If you do this often you may consider using a helper function to zip two lists into one pair list:
public static <A, B> List<Pair<A, B>> zip(List<A> listA, List<B> listB) {
if (listA.size() != listB.size()) {
throw new IllegalArgumentException("Lists must have same size");
}
List<Pair<A, B>> pairList = new LinkedList<>();
for (int index = 0; index < listA.size(); index++) {
pairList.add(Pair.of(listA.get(index), listB.get(index)));
}
return pairList;
}
You will also need a Pair implementation. Apache commons lang package has a proper one.
And with these you can now elegantly iterate on the pairlist:
ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
for (Pair<JRadioButton, Integer> item : zip(category , cat_ids)) {
// do something with JRadioButton
item.getLeft()...
// do something with Integer
item.getRight()...
}
Try this
ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
for (int i = 0; i < category.size(); i++) {
JRadioButton cat = category.get(i);
Integer id= cat_ids.get(i);
..
}
ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
Iterator<JRadioButton> itrJRB = category.iterator();
Iterator<Integer> itrInteger = cat_ids.iterator();
while(itrJRB.hasNext() && itrInteger.hasNext()) {
// put your logic here
}
Although you are expecting both sizes to be same, just to be on safer side get the sizes for both of them and make sure they are equal.
Let that size value be count. Then use generic for loop, iterate till count and acess the values as array indexes. If 'i' is the index, then acess as below in the for loop.
category[i] and cat_ids[i]
category[i].isSelected() and so on

Categories