Hi everybody I am trying to get values from an ArrayList I created. I have some indexes, and I want to print the data ONLY between the indexes I want, so far I ave done this, but it does not seem to work. I think the get() is not valid for want I want... Any ideas?
public static void main(String[] args) throws Exception {
Scanner dataSc = new Scanner(new FileReader("StudData1.txt"));
ArrayList<String> ArrayData = new ArrayList<String>();
ArrayList<String> idData = new ArrayList<String>();
ArrayList<String> idIndex = new ArrayList<String>();
int b = 0;
int a = 0;
int i = 0;
while (dataSc.hasNextLine()) {
String data = dataSc.nextLine();
ArrayData.add(i, data);
if (data.contains("ID: ")) {
idData.add(a, data);
idData.set(a, (idData.get(a).replaceAll("[\\D]", "")));
a++;
b++;
}
i++;
idIndex.add(b, Integer.toString(i));
}
int idSt1 = Integer.parseInt(idData.get(0));
int idSt2 = Integer.parseInt(idData.get(1));
int idSt3 = Integer.parseInt(idData.get(2));
int idxID1 = Integer.parseInt(idIndex.get(0));
int idxID2 = Integer.parseInt(idIndex.get(1));
int idxId3 = Integer.parseInt(idIndex.get(2));
if (idSt1 < idSt2 && idSt2 < idSt3) {
System.out.println(ArrayData.get(idxID1-3 , idxID2-3 );}
}
}
}
Its easy done with a for-loop.
for(int i = startindex+1; i<endindex; i++) {
System.out.println(ArrayData.get(i));
}
This loop will print all objects in the arraylist that are between the given indices.
But there is no method called get() which returns a collection of items that are between to given indices, you can only use the subList(arg0, arg1) method to creat a subcollection and then iterate over this subcollection. Take a look at the Docs http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#get%28int%29
Example:
List<String> al = new ArrayList<>();
al.add("a");
al.add("b");
al.add("c");
al.add("d");
List<String> sublist = al.subList(0, 3); //inclusive index 0, exclusive index 3
for(String s : sublist)
System.out.println(s);
Output: a, b, c
Problem is in your code:
System.out.println(ArrayData.get(idxID1-3 , idxID2-3 );
The get method of class ArrayList accepts only one argument, here you are passing two.
You can use subList(int fromIndex, int toIndex) to get your desired result.
You can take range of values by index from ArrayList as follows.
List<String> list=new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
for(int i=0;i<4;i++){
if(i<=2 && i>=1){
System.out.println(list.get(i));
}
}
i would do it like that
if (idSt1 < idSt2 && idSt2 < idSt3) {
for (int j = idxID1-3; j < idxID2-3; j++){
System.out.println(ArrayData.get(j));
}
}
Related
I am creating an ArrayList of String Arrays in Java.. The code for the same is follows..
ArrayList<String[]> al = new ArrayList<String[]>();
for(int i = 0; i < t; i++) { // t is input by user representing size of arraylist
int k = sc.nextInt();
String[] s = new String[k]; // k string values input by user
}
Iterating to print the values of ArrayList
Iterator it = al.iterator();
while(it.hasNext()){
for(int i = 0; i < (it.next(new String[])).length; i++) { // error for dimension missing
System.out.println((it.next(new String[])).length); // error for dimension missing
}
}
I get an error of "array dimension missing" in the indicated lines. Please suggest how to convert ArrayList Object as String Array.
Try this
Iterator<String[]> it = al.iterator();
while(it.hasNext()){
String temp [] = it.next();
for(int i = 0; i < temp.length; i++) {
System.out.println(temp.length);
}
}
your new String[]
requires size, because you're making new array i.e
String[] myStringArray = new String[5];
also, your iteration to print values make no sense, try :
for(String[] stringArray: al) {
System.out.println("Size: " + stringArray.length);
for(String s: stringArray) {
System.out.println(s);
}
}
Need to do a method which takes ArrayList<ArrayList<<Integer>> and an Integer which then returns an ArrayList<ArrayList<<Integer>> from the orginal ArrayList<ArrayList<<Integer>> which do not contain the Integer argument e.g
ArrayList<ArrayList<<Integer>>
[[1,2,3],[7,5],[4,4,2],[8,12,3]] and Integer 2 should return
[[7,5],[8,12,3]]. arraylist of arraylist integers.
not entirely sure how to access the inner loop
You can use contains() rather than worrying about writing an inner loop yourself.
Also, removing elements from lists while iterating is tricky. So, since you are not modifying the list and seem to be expected to return one, then just make a new list and add rather than remove.
public static ArrayList<ArrayList<Integer>> removeTheNumber(ArrayList<ArrayList<Integer>> n , Integer p){
ArrayList<ArrayList<Integer>> a = new ArrayList<>();
for(int i=0; i < n.size(); i++){
ArrayList<Integer> innerList = n.get(i);
if (!innerList.contains(p)) a.add(innerList);
}
return a;
}
You can use .contains of the inner lists to check as Integer class supports this. Below is a function and its test.
public ArrayList<ArrayList<Integer>> removeTheNumber(ArrayList<ArrayList<Integer>> lists, Integer n) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
for (ArrayList<Integer> list: lists ) {
if (!list.contains(n))
result.add(list);
}
return result;
}
#Test
public void testRemoveNumber() {
ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
lists.add(Lists.newArrayList(2,7,8));
lists.add(Lists.newArrayList(6,7,9));
lists.add(Lists.newArrayList(3,2,6));
ArrayList<ArrayList<Integer>> result = removeTheNumber(lists, 2);
Assert.assertArrayEquals(lists.get(1).toArray(new Integer[]{}), result.get(0).toArray(new Integer[]{}));
result = removeTheNumber(lists, 7);
Assert.assertArrayEquals(lists.get(2).toArray(new Integer[]{}), result.get(0).toArray(new Integer[]{}));
result = removeTheNumber(lists, 6);
Assert.assertArrayEquals(lists.get(0).toArray(new Integer[]{}), result.get(0).toArray(new Integer[]{}));
}
If you want to use two loops you can write it like this (where array is your input array, and toSearch is your integer):
ArrayList<ArrayList<Integer>> arrayToReturn = new ArrayList<>();
for(ArrayList<Integer> listInner : array){
boolean found = false;
for(Integer elem : listInner) {
if (elem == toSearch)
found=true;
}
if(found!=true)
arrayToReturn.add(listInner);
}
arrayToReturn.stream().forEach(System.out::println);
Of course i reccomend to use java 8, and then you can simply write it like this:
arrayToReturn = array.stream().filter(elem ->
!elem.contains(toSearch)).collect(
Collectors.toCollection(ArrayList<ArrayList<Integer>>::new));
arrayToReturn.stream().forEach(System.out::println);
Let's pretend you have
ArrayList<ArrayList<Integer>> myArrayList = [[1,2,3],[7,5],[4,4,2],[8,12,3]];
for (int i = 0; i < myArrayList.length; i++) {
//...
}
Your variable i is iterating through the initial ArrayList, which contains another ArrayList. So, myArrayList[i] will yield another ArrayList, which also has a length.
Building on this we have:
for (int i = 0; i < myArrayList.length; i++) {
ArrayList<Integer> inner = myArrayList.get(i);
for (int j = 0; j < inner.length; j++) {
//now we may check for the existence of our integer
}
}
I am trying to combine multiple String lists.
Say I have two (could be more) lists of the same size:
List<String> list1 = Arrays.asList("1One","1Two","1Three");
List<String> list2 = Arrays.asList("2One","2Two","2Three");
I want to combine the value of the corresponding indexes and place them into a new list:
List3 = new {"1One2One", "1Two2Two", "1Three2Three"};
Currently I have a list of 2 objects, each object contains the list that I want to combine the elements within.
So I want to combine element 1 in the list from object 1 with element 1 from the list from object 2.
This is what I have attempted:
public void generateFileList(List<Object> cl){
int count = 0;
String temp = "";
for(int i = 0; i < cl.size(); i++){
for (int x = 0; x < cl.get(i).getItemList().size(); x++) {
if (count == x){
temp += cl.get(i).getListItem(x);
break;
}
}
count++;
textList.add(temp);
}
}
public void test(){
for(String s : textList){
System.out.println("List Element - " + s);
}
System.out.println(textList.size());
}
Which prints out:
List Element - 1One
List Element - 1One1Three
What am I doing wrong here?
First, the code you have won't compile. It should be:
List<String> list1 = Arrays.asList("1One","1Two","1Three");
List<String> list2 = Arrays.asList("2One","2Two","2Three");
Next, it is best to use an Iterator than access a List by index:
public List<String> concat(final List<String> list1, final List<String> list2) {
final Iterator<String> i1 = list1.iterator();
final Iterator<String> i2 = list2.iterator();
final List<String> combined = new ArrayList<>();
while (i1.hasNext() && i2.hasNext()) {
combined.add(i1.next() + i2.next());
}
return combined;
}
For an arbitrary number of List:
public List<String> concat(final List<String>... lists) {
final List<Iterator<String>> it = new LinkedList<>();
for (List<String> l : lists) {
it.add(l.iterator());
}
final List<String> combined = new ArrayList<>();
outer:
while (true) {
final StringBuilder sb = new StringBuilder();
for (final Iterator<String> i : it) {
if (!i.hasNext()) {
break outer;
}
sb.append(i.next());
}
combined.add(sb.toString());
}
for (final Iterator<String> i : it) {
if (i.hasNext()) {
throw new IllegalArgumentException("Lists not the same length.");
}
}
return combined;
}
If the lists have the same size, just have a for loop from 0 to list size, and add in the new list the concatenation of the elements from the same position in the two lists, like for (int i =0; i< list1.size(); i++) { resultedlist.add(list1.get(i) + list2.get(i))}
Presuming the 2 lists are the same size:
List<String> list1 = new {"1One","1Two","1Three"};
List<String> list2 = new {"2One","2Two","2Three"};
List<String> list3 = new ArrayList<>();
for (int i = 0; i < list1.size(); i++) {
list3.add(list1.get(i) + list2.get(i));
}
Am doing a simple android application.In that I am deleting an element from array using the following code.
arr_fav = {"1","2","3"};
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
arr_fav[1] = null;
} }
By doing this am getting the array like arr_fav = {"1",null,"3"}.But I want like arr_fav = {"1","3"}.How to delete an element.Am new to this android development.Please help me to solve this.
its better to use arraylist
arr_fav = {"1","2","3"};
List<String> numlist = new ArrayList<String>();
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
// No operation here
}
else
{
numlist.add(arr_fav[i]);
}
}
arr_fav = numlist .toArray(new String[numlist .size()]);
You don't.
Arrays can not be resized.
You would need to create a new (smaller) array, and copy the elements you wished to preserve into it.
A better Idea would be to use a List implementation that was dynamic. An ArrayList<Integer> for example.
Arrays in Java are not dynamic, you can use an ArrayList instead.
You can copy the array elements that you want into a new array
j = 0;
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id != Integer.parseInt(arr_fav[i]))
{
arr_new[j++] = arr_fav[i];
} }
Use an ArrayList instead of an array. It supports features like deleting any element, dynamic size, and many more.
ArrayList<String> arr_fav_list = new ArrayList<String>();
arr_fav_list.addAll(arr_fav);
arr_fav_list.remove(1);
This will do the job ...
List x = new ArrayList(Arrays.asList(arr_fav));
x.remove(String.valueOf(current_id));
arr_fav = x.toArray();
try this:
ArrayList<String> rm = new ArrayList<String>();
rm .addAll(arr_fav);
rm .remove(1);
Try something like this
int[] intAry = new int[5];
// populate array with 0 to 4
for (int i=0; i < intAry.length; i++) {
intAry[i] = i;
}
List<Integer> aList = Arrays.asList(intAry); // change the array to a list of integers
aList.remove(3); // remove the item 3 (4th index)
aList.toArray(intAry); // convert list back to array
System.out.println("size of array=" + intAry.size()); // output array size should be 4
for (int i=0; i < intAry.length; i++) {
System.out.print(intAry[i] + " "); // should output "0 1 2 4 "
}
set
array_fav[1]=array_fav[2];
array_fav[2]=null;
You can do it using the following method..
public static String[] removeElements(String[] input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
OR you could use ArrayUtils.
array = ArrayUtils.removeElement(array, element)
For simple arrays like this you can't do this in this way
here is the full sample code for this
int current_id = 2;
String[] arr_fav = { "1", "2", "3" };
for (int i = 0; i < arr_fav.length; i++) {
if (current_id == Integer.parseInt(arr_fav[i])) {
String[] arr_fav_tem = new String[arr_fav.length - 1];
arr_fav[1] = null;
int counter = 0;
for (int j = 0; j < arr_fav.length; j++) {
if (arr_fav[j] != null) {
arr_fav_tem[counter] = arr_fav[j];
counter++;
}
}
arr_fav = arr_fav_tem;
}
}
for (int i = 0; i < arr_fav.length; i++) {
System.out.println(arr_fav[i]);
}
String[] arr_fav =
{ "1", "2", "3" };
List<String> myList = Arrays.asList(arr_fav);
String currentId = String.valueOf(current_id);
for (int i = 0; i < arr_fav.length; i++)
{
if (arr_fav[i].equals(currentId))
{
myList.remove(i);
}
}
private String[] removeItem(String[] names,
int position) {
ArrayList<String> al_temp=new ArrayList<String>();// temporary ArrayList
for(int i=0;i<names.length;i++)
{
al_temp.add(names[i]);
}
al_temp.remove(position);
names= new String[al_temp.size()];//array cleared with new size
for(int i=0;i<al_temp.size();i++)
{
names[i]=al_temp.get(i);
}
return names;
}
Copy this method:
private static String[] deleteElement(String stringToDelete, String[] array) {
String[] result = new String[array.length];
int index = 0;
ArrayList<String> rm = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
rm.add(array[i]);
}
for(int i = 0; i < array.length; i++) {
if(array[i].equals(poistettava)) {
index = i;
}
}
rm.remove(index);
result = rm.toArray(new String[rm.size()]);
return result;
}
To delete element:
String[] array = {"1", "2", "3"};
array = deleteElement("3", array);
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:
ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
int element = listB.get(i);
for(int j=0; j<listA.size(); j++) {
if(listA.get(j) == element) listC.add(j);
}
}
I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.
If you had to use an ArrayList, you could create a HashSet from the ArrayList. This would make the call to contains O(1). It would take O(n) to create the HastSet. If you could start with a HashSet, that would be best.
public static void main(String[] args)
{
List listA = new ArrayList();
listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);
List listB = new ArrayList();
listB.add(2);
listB.add(4);
Set hashset = new HashSet(listA);
for(int i = 0; i < listB.size(); i++)
{
if(hashset.contains(listB.get(i)))
{
listC.add(i);
System.out.println(i);
}
}
}
The Guava libraries come with a method
"SetView com.google.common.collect.Sets.intersection(Set a, Set b)
that will give the elements contained in both sets, but not the indexes. Although it should be easy to get the indexes afterwards.
Simple:
List<Integer> listA = new ArrayList<Integer>();
listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);
List<Integer> listB = new ArrayList<Integer>();
listB.add(2);
listB.add(4);
List<Integer> listC = new ArrayList<Integer>();
for ( Integer item : listA ) {
int index = listB.indexOf( item );
if ( index >= 0 ) {
listC.add(index);
}
}
But this only works if there is no repetition, if there are repeated indexes you have to do it the way you did, navigating the full list.
EDIT
I thought you wanted the elements, not indexes, sets are not going to give you indexes, only the elements.
Assuming there's no duplicate values, why not use ArrayList.indexOf?
public final class ArrayListDemo {
public static void main(String[]args){
findIndices(createListA(), createListB());
}
private static final List<Integer> createListA(){
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(5);
return list;
}
private static final List<Integer> createListB(){
List<Integer> list = new ArrayList<Integer>();
list.add(0);
list.add(2);
list.add(3);
list.add(4);
return list;
}
private static void findIndices(List<Integer> listA, List<Integer> listB){
for(int i = 0; i < listA.size(); i++){
// Get index of object in list b
int index = listB.indexOf(listA.get(i));
// Check for match
if(index != -1){
System.out.println("Found match:");
System.out.println("List A index = " + i);
System.out.println("List B index = " + index);
}
}
}
}
Output
Found match:
List A index = 1
List B index = 2
If list A and list B are sorted in the same order (I'll assume ascending, but descending works as well) this problem has an O(n) solution. Below is some (informal, and untested) code. When the loop exits, indexMap should contain the indices of every element in list A that match an element in list B and the index of the matched element in list B.
int currentA;
int currentB;
int listAIndex = 0;
int listBIndex = 0;
Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
currentA = listA.get(listAIndex);
currentB = listB.get(listBIndex);
while ((listAIndex < listA.length) && (listBIndex < listB.length))
{
if (currentA == currentB)
{
indexMap.put(listAIndex, listBIndex);
++listAIndex;
}
else if (currentA < currentB)
{
++listAIndex;
}
else // if (currentA > currentB)
{
++listBIndex;
}
}
Using Apache CollectionUtils, there are plenty of options