add data after every 2nd element in an array - java

I want to add object/data in an array after every 2nd element ....just for making more clear I am going to use a simple example
I have arrayList of :
List<Object> list = new ArrayList<>();
list.add("messi");
list.add("ronaldo");
list.add("rooney");
list.add("pogba");
list.add("hazard");
print(list);
//output : [messi, ronaldo, rooney, pogba,hazard]
What I want is:
//[messi, ronaldo, DATA, rooney, pogba, DATA, hazard]
how I can achieve this.
Adding data in an array after every 2nd element.

By maintaining a counter.
public class Main {
public static void main(String[] args) {
List<Object> list = new ArrayList<>();
list.add("messi");
list.add("ronaldo");
list.add("rooney");
list.add("pogba");
list.add("hazard");
int counter = 0 ;
List<Object> data = new ArrayList<>();
for(Object obj : list){
data.add(obj);
counter = counter + 1;
if(counter%2 == 0)
data.add("DATA");
}
for(Object obj : data)
System.out.println(obj);
}
}

So, you can do is create a new list to store the old data with new object:
List<Object> list = new ArrayList<>();
List<Object> newlist = new ArrayList<>();
list.add("messi");
list.add("ronaldo");
list.add("rooney");
list.add("pogba");
list.add("hazard");
for(int i = 0; i < list.size(); i++) {
if(i%2==0) {
// Add DATA after 2 items
newlist.add(data);
}
newlist.add(list.get(i));
}
Please someone format since I'm writing from my phone.

class sample {
public static void main(String[] args) {
List<Object> list = new ArrayList<>();
sample.addList("messi", list);
sample.addList("ronaldo", list);
sample.addList("rooney", list);
sample.addList("pogba", list);
sample.addList("hazard", list);
System.out.println(list);
}
private static void addList(String value, List<Object> objects) {
if (!objects.isEmpty() && (objects.size() % 3 == 2)) {
objects.add("Data");
}
objects.add(value);
}
}
You can create one utility method as mentioned above.
For every time before adding element check that if list.size() % 3 == 2 then add extra element.
This will help you.

Look at the desired output and the indexes of the inserted DATA values:
[messi, ronaldo, DATA, rooney, pogba, DATA, hazard]
0 1 2 3 4 5 6
The DATA values go in index 2, 5, 8, 11, ...
Which means it's a simple for loop calling add(int index, E element):
List<Object> list = new ArrayList<>();
list.add("messi");
list.add("ronaldo");
list.add("rooney");
list.add("pogba");
list.add("hazard");
System.out.println(list);
for (int i = 2; i < list.size(); i += 3) {
list.add(i, "DATA");
}
System.out.println(list);
Output
[messi, ronaldo, rooney, pogba, hazard]
[messi, ronaldo, DATA, rooney, pogba, DATA, hazard]

Related

how can I slice my list in chunks before I call a method on each of the chunk?

I have a List of objects in Java:
ArrayList<myObj> objs = generateObjs();
and I have a method responsible for sending the objects further, this method takes the list above as an argument:
sendObjectsFurther(objs)
I want to split the list objs so that I can send further objects in a group of five elements.
What is the best approach to do it?
I thought about implementing something like this:
public void sendSliced(List objs) {
ArrayList<myObj> tempList = new ArrayList()<>;
for (int i = 0; i < objs.size(); i++) {
tempList.add(objs.get(i));
if (i % 5 == 0) {
sendObjectsFurther(tempList);
tempList.clear();
}
}
}
but I think it won't cover all edge cases, could you help me with that? Thanks!
You can use Java 8 Stream API for this.
List<myObj> objs = generateObjs();
int chunkSize = 5;
AtomicInteger counter = new AtomicInteger();
Collection<List<myObj>> result = objs.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize))
.values();
for (myObj chunk: result){
sendObjectsFurther(tempList);
}
Also, class names should start with an upper case.
You could use guava Lists.partition which will split into sub lists.
Example :
for (List<String> slice : Lists.partition(bigList, 5)) {
send(slice);
}
The relevant javadoc link https://guava.dev/releases/23.0/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int-
You can add one line to your code
public void sendSliced(List objs) {
ArrayList<myObj> tempList = new ArrayList()<>;
for (int i = 0; i < objs.size(); i++) {
tempList.add(objs.get(i));
if (i % 5 == 0) {
sendObjectsFurther(tempList);
tempList.clear();
}
}
sendObjectsFurther(tempList);
}
Which will add remaining items.
Please check the below code, here each sublist will represents a chunk with 5 elements, So suppose I have total of 8 elements in my obj list, so first chunk will have 5 and next chunk will have 3.
public static void main(String[] args) throws IOException {
List<Employee> objs = new ArrayList<>();
objs.add(new Employee(1));
objs.add(new Employee(2));
objs.add(new Employee(3));
objs.add(new Employee(4));
objs.add(new Employee(5));
objs.add(new Employee(6));
objs.add(new Employee(7));
objs.add(new Employee(8));
sendSliced(objs);
}
private static void sendSliced(List<Employee> objs) {
int chunkSize = 5;
final AtomicInteger counter = new AtomicInteger();
Collection<List<Employee>> subLists = objs.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize))
.values();
subLists.stream().forEach( sublist -> System.out.print(sublist));
subLists.stream().forEach( sublist -> sendObjectsFurther(sublist));
}
}
class Employee {
private int id;
Employee(int id) {
this.id = id;
}
}
Ouput Will be something like:
index = 0
[com.practice.stackoverflow.Employee#77459877, com.practice.stackoverflow.Employee#5b2133b1, com.practice.stackoverflow.Employee#72ea2f77, com.practice.stackoverflow.Employee#33c7353a, com.practice.stackoverflow.Employee#681a9515]
index=1
[com.practice.stackoverflow.Employee#3af49f1c, com.practice.stackoverflow.Employee#19469ea2, com.practice.stackoverflow.Employee#13221655]

Is there any way to delete some elements from a given ArrayList after adding the same elements to a new ArrayList?

For example, there is a list of elements.
We call the streamMethod on this list. Now we want to extract a certain element from the list by a condition and add it to a new list.
Example:
List<Integer> intList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
intList.add(i);
}
public static List<Integer> getIntFive(List<Integer> list) {
return list.stream().filter(i -> i.equals(5)).collect(Collectors.toList());
}
public static List<Integer> getIntEight(List<Integer> list) {
return list.stream().filter(i -> i.equals(8)).collect(Collectors.toList());
}
Is there a way to delete the items added to the new list from the original list? Could one link another stream behind the first one and thus influence the property of the original list?
Closer to your current implementation, another way to perform the operation would be:
public static List<Integer> getIntEight(List<Integer> list) {
List<Integer> res = list.stream()
.filter(i -> i.equals(8))
.collect(Collectors.toList());
list.removeAll(res);
return res;
}
You can't remove while streaming, but there is no harm in iterating twice, for example:
List<Integer> initial = new ArrayList<>(List.of(1, 2, 3, 4, 5));
List<Integer> result = new ArrayList<>();
initial.forEach(x -> {
if (x > 3) {
result.add(x);
}
});
// or simply : initial.removeAll(result);
initial.removeIf(result::contains);
System.out.println(initial); // 1,2,3
System.out.println(result); // 4,5

how to Add ArrayList in ArrayList

I got a problem when insert an ArrayList into ArrayList.
My source code:
import java.util.ArrayList;
public class Ask {
public static void main(String[] args) {
ArrayList<String> mentah = new ArrayList<String>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
ArrayList<ArrayList<String>> result =new ArrayList<ArrayList<String>>();
result.add(mentah);
}
}
How can I create a list based on that data; that will look like:
[[data1,data2,data3],[data4,data5,data6],[data7,data8,data9,data10]]
10 div 3 is 3 (so 3 elements per sublist)
10 mod 3 is 1 (so last sublist has 4 entries)
10 divide by 3 is
3 3 4
Just upgraded the answer of #Narayana Ganesh:
ArrayList<String> mentah = new ArrayList<String>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
List<List<String>> result = new ArrayList<List<String>>();
for (int j= 0; j< mentah.size() ; j+=3) {
int end = mentah.size() <= j+2 ? mentah.size() : j+3;
if(mentah.size() - j == 4) end = end +1;
if(j != 9) result.add(mentah.subList(j, end));
}
System.out.println(result);
}
Result:
[[Reza, Fata, Faldy], [Helsan, Dimas, Mamun], [Erik, Babeh, Tio, Mamang]]
A more generic solution would look like:
List<String> allNames = Arrays.asList("Reza", "Fata", ...
List<List<String>> slicedNames = new ArrayList<>();
List<String> sublist = new ArrayList<>();
int sublistTargetLength = 3;
for (String name : allNames) {
sublist.add(name);
if (sublist.size() == sublistTargetLength) {
slicedNames.add(sublist);
sublist = new ArrayList<>();
}
}
if (sublist.size() > 0) {
slicedNames.get(slicedNames.size()-1).addAll(sublist);
}
Some notes:
The above iterates your initial list of names (which can created using that single call to Arrays.asList()); and puts the entries into same-sized lists; which are then added to the slicedNames list of list.
If there is any "remaining" data; that is simply added to the last element of the list of list.
You should prefer to use the interface type List for your variable types; you only use the specific implementation class (ArrayList) when instantiating the list
When iterating anything, prefer the for-each looping style when possible
Try this. You can achieve this using subList method.
import java.util.ArrayList;
import java.util.List;
public class Ask {
public static void main(String[] args) {
ArrayList<String> mentah = new ArrayList<String>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
List<List<String>> result = new ArrayList<List<String>>();
for (int j= 0; j< mentah.size() ; j+=3) {
int end = mentah.size() <= j+2 ? mentah.size() : j+3;
result.add(mentah.subList(j, end));
}
for (List<String> item : result) {
System.out.println(" - -"+item);
}
}
}
First create sublists with a maximal size of 3 which will give you something like this
[[Reza, Fata, Faldy], [Helsan, Dimas, Mamun], [Erik, Babeh, Tio], [Mamang]]
then check if the last sublist size is less than 3 if yes add this to the second last sublist and remove the last one
public class Example {
public static void main(String[] args) {
List<String> mentah = new ArrayList<>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
List<List<String>> parts = new ArrayList<>();
int sizeOfOriginalList = mentah.size();
int sizeOfSubLists = 3;
for (int i = 0; i < sizeOfOriginalList; i += sizeOfSubLists) {
parts.add(new ArrayList<>(mentah.subList(i, Math.min(sizeOfOriginalList, i + sizeOfSubLists))));
}
if(parts.get(parts.size()-1).size()<sizeOfSubLists){
parts.get(parts.size()-2).addAll(parts.get(parts.size()-1));
parts.remove(parts.get(parts.size()-1));
}
System.out.println(parts);
}
}

Remove all the odd numbers in an ArrayList

I already wrote code to remove all the odd numbers in an ArrayList.
import java.util.*;
public class Odd {
public static void main (String [] args) {
ArrayList <Integer> mylist = new ArrayList<>(Arrays.asList(1, 2, 4, 6, 7));
System.out.println(odd(mylist));
}
public static int odd(ArrayList<Integer> list) {
if (list.isEmpty()) { throw new Error(); }
int a = list.get(0);
List<Integer> toRemove = new ArrayList<>();
for (int si : list) {
if (si % 2 != 0) { toRemove.add(si); }
}
list.removeAll(toRemove);
return a;
}
}
But somehow the result is always 1.Can someone point out what is my mistake?Thank you in advance
There are two problems with your code:
(1) You need to return the list object (contains Integers) after the removal of odd numbers
(2) In order to return the list, you need to change the method signature from int to List<Integer> (as return type):
You can refer the below code with comments:
//change the method signature to return List<Integer>
public static List<Integer> odd(ArrayList<Integer> list) {
if (list.isEmpty()) { throw new Error(); }
List<Integer> toRemove = new ArrayList<>();
for (int si : list) {
if (si % 2 != 0) { toRemove.add(si); }
}
list.removeAll(toRemove);
return list;//return list, not int
}
Check this line:
int a=list.get(0);
You are reading only the first element of the list, which is 1, and not iterating through it.
Use either an iterator (for each, for example) or a regular for loop (using the item count from list).
As other people have indicated, the problem is that you're returning this:
int a = list.get(0);
Thus, you'll always get the first item in the list, regardless of what you do to it after you retrieve it.
Getting rid of a completely and just returning list will fix that issue.

Get value (String) of ArrayList<ArrayList<String>>(); in Java

I know it's simple question, but in
ArrayList<ArrayList<String>> collection;
ArrayList<String> listOfSomething;
collection= new ArrayList<ArrayList<String>>();
listOfSomething = new ArrayList<String>();
listOfSomething.Add("first");
listOfSomething.Add("second");
collection.Add(listOfSomething);
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
I want to take String from ArrayList of ArrayList, and I don't know how to do that. For example I go
ArrayList<String> myList = collection.get(0);
String s = myList.get(0);
and it works! but:
Big update:
private List<S> valuesS;
private List<Z> valuesZ;
ArrayList<ArrayList<String>> listOfS;
ArrayList<String> listOfZ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Zdatasource = new ZDataSource(this);
Zdatasource.open();
valuesZ = Zdatasource.getAllZ();
Sdatasource = new SDataSource(this);
Sdatasource.open();
valuesS = Sdatasource.getAllS();
List<Map<String, String>> groupData
= new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData
= new ArrayList<List<Map<String, String>>>();
listOfS = new ArrayList<ArrayList<String>>();
listOfZ = new ArrayList<String>();
for (S i : valuesS) { // S is class
for (Z j : valuesZ) { // Z is class
if(j.getNumerS().equals(i.getNumerS())) {
listOfZ.add(j.getNumerZ());
}
else
{
//listOfZ.add("nothing");
}
}
listOfS.add(listOfZ);
if(!listOf.isEmpty()) listOfZ.clear();
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
try
{
ArrayList<String> myList = listOfS.get(groupPosition);
String s = myList.get(childPosition);
PrintToast("group "+Integer.toString(groupPosition)+", child "+Integer.toString(childPosition) + " , "+ s);
}
catch(Exception e)
{
Log.e("FS", e.toString());
}
return true;
}
return me java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
when I click on item which really should exist. I didn't show code which generate ListView, but I can tell you that my listOfS contains 3 items:
first is Null listOfZ, second listOfZ got 2 elements, third listOfZ got 1 element.
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.
Notice both collection.Add(listOfSomething); save two references to the same arraylist object.
You need to create two different instances for two elements:
ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();
ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");
ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");
collection.Add(listOfSomething1);
collection.Add(listOfSomething2);
Because the second element is null after you clear the list.
Use:
String s = myList.get(0);
And remember, index 0 is the first element.
The right way to iterate on a list inside list is:
//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
ArrayList<String> currentList = collection.get(i);
//now iterate on the current list
for (int j = 0; j < currentList.size(); j++) {
String s = currentList.get(1);
}
}
A cleaner way of iterating the lists is:
// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
for (String string : innerList) {
// do stuff with string
}
}
I have String array like this
We have to pass data through response.body.getdata and this data pass in constructor like this,
List taginnerData;
"data": [
"banana",
"apple",
"grapes",
"Pears",
"Mango",
"Cherry",
"Guava",
"TorontoVsMilwaukee_12Jan19"
]
String[] myArray = new String[taginnerData.size()];
for (int i = 0; i < taginnerData.size(); i++) {
myArray[i] = String.valueOf(taginnerData.get(i));
holder.tv_channel_name.setText("" +taginnerData.get(i));
//we get any value from here to set in adapter
}

Categories