The method on the top should merge two String elements in an ArrayList that are side by side with each other. If the length of the ArrayList is Odd the last String element should be left unchanged.
But the problem is that is this way the program leaves the first String element alone, while the others are merged nicely. The output looks like this:
[1, 23, 45, 67, 89]
although it has to look like this:
[12, 34, 56, 78, 9]
How is it possible to fix the problem? Preferably without using the Iterator.
import java.util.ArrayList;
public class Main {
public static ArrayList<String> clump (ArrayList<String> list)
{
for (int i =0; i< list.size(); i++)
//for (int i = list.size()-1; i >=0; i--)
{
// if (i == 0)
if ((list.size() + i) % 2 == 0) {
System.out.println(list);
System.out.println("list size is " + list.size());
String newElement = list.get(i) + list.get(i+ 1);
list.remove(i);
list.remove(i);
list.add(i, newElement);
//System.out.println(list);
}
else {
continue;
}
}
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
System.out.println(clump(list));
}
}
Your code seems to work fine if the input list has even number of elements. For the case when you have odd number of elements in the list, remove the last element from the list and save it temporarily before running your code. Add the last element back to the output returned.
This can be one solution (may not be the best solution):
import java.util.ArrayList;
public class Main {
public static ArrayList<String> clump (ArrayList<String> list)
{
// BEGIN CHANGES MADE
String temp = null;
int size = list.size();
if ((size%2) != 0)
{
temp = list.remove(size-1);
}
// END CHANGES MADE
for (int i =0; i< list.size(); i++)
{
if ((list.size() + i) % 2 == 0) {
System.out.println(list);
System.out.println("list size is " + list.size());
String newElement = list.get(i) + list.get(i+ 1);
list.remove(i);
list.remove(i);
list.add(i, newElement);
//System.out.println(list);
}
else {
continue;
}
}
// BEGIN CHANGES MADE
if (temp != null)
{
list.add(temp);
}
// END CHANGES MADE
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
//list.add("0");
System.out.println(clump(list));
}
}
You don't need to check if ((list.size() + i) % 2 == 0). On every iteration you can concatenate adjacent elements.
Also, you will need to loop until i < list.size()-1 instead of i < list.size() because when you remove the 2nd last element, you are already at the last index.
So remove the if-else block if ((list.size() + i) % 2 == 0).
and replace:
for (int i =0; i< list.size(); i++)
with:
for (int i = 0; i < list.size() - 1; i++)
Here is a working version of your program:
import java.util.ArrayList;
class So {
public static ArrayList<String> clump(ArrayList<String> list) {
for (int i = 0; i < list.size() - 1; i++)
// for (int i = list.size()-1; i >=0; i--)
{
// if (i == 0)
System.out.println(list);
System.out.println("list size is " + list.size());
String newElement = list.get(i) + list.get(i + 1);
list.remove(i);
list.remove(i);
list.add(i, newElement);
// System.out.println(list);
}
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
System.out.println(clump(list));
}
}
I hope it helps you out. I used your code. It was enough good idea. Some change helped on it to work fine. Try it out! :D
import java.util.ArrayList;
public class Main {
public static ArrayList<String> clump (ArrayList<String> list)
{
int halfSize = list.size()/2;
for (int i =0; i < halfSize; i++) {
System.out.println(list);
String newElement = list.get(i) + list.get(i+1);
list.remove(i);
list.remove(i);
list.add(i, newElement);
}
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
list.add("10");
list.add("11");
list.add("12");
list.add("13");
System.out.println(clump(list));
}
}
private static ArrayList<String> clump(ArrayList<String> list) {
ArrayList<String> res = new ArrayList<String>();
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
res.add(itr.next() + (itr.hasNext() ? itr.next() : ""));
}
return res;
}
ArrayList<Integer> getMinCoins = new ArrayList<Integer>(); // function to receive change in the form of coins
{
for (int i: coins){
getMinCoins.add(i);
System.out.println(getMinCoins);
}
}
Related
I have this code, duplicate elements are removed from the array, it works, but I don't know how to make it recursive
public static void main(String[] args) {
dupe cadena= new dupe();
String arraycar[]={"h","i","e","l","o","i","s","e"};
System.out.println(arraycar);
for(int i=0; i<arraycar.length; i++){
for (int j=0; j<arraycar.length-1; j++){
if (i!=j){
if (arraycar[i]==arraycar[j]){
arraycar [i]="";
}
}
}
}
int n= arraycar.length;
for (int k=0; k<=n-1; k++){
if (arraycar[k]!=""){
System.out.println(arraycar[k]);
}
}
}
In current implementation there are nested loops and in the inner loop the duplicate elements are replaced with empty string.
A recursive implementation may replace the outer loop, so the recursive method should have an index argument, and the exit condition will be met when the index achieves the length of the input array.
Example implementation:
public static void removeDuplicates(String[] arr) {
removeDuplicates(1, arr);
}
public static void removeDuplicates(int start, String[] arr) {
if (start >= arr.length) {
return;
}
String val = arr[start - 1];
int nonDup = -1; // the index of the first non-empty string to use as start
for (int i = start; i < arr.length; i++) {
if (val.equals(arr[i])) {
arr[i] = "";
}
else if (nonDup == -1) {
nonDup = i;
}
}
if (nonDup >= start) { // non-duplicate candidates are available
removeDuplicates(nonDup + 1, arr);
}
}
Test
String arraycar[]={"h","h", "i","e","l","o","i","s","e", "s"};
Arrays.stream(arraycar).filter(Predicate.not(""::equals)).forEach(s -> System.out.print(s + " "));
removeDuplicates(arraycar);
System.out.println("\nduplicates removed:");
Arrays.stream(arraycar).filter(Predicate.not(""::equals)).forEach(s -> System.out.print(s + " "));
Output
h h i e l o i s e s
duplicates removed:
h i e l o s
However, one of the simplest way would be to use Stream::distinct to get rid of duplicates (no recursion needed):
String[] noDups = Arrays.stream(arraycar).distinct().toArray(String[]::new);
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));
}
This question already has answers here:
Placing null at the end of the List
(5 answers)
Closed 8 years ago.
I have an arrayList of object like that: [object 1, object 2, null,null,..,null , object 3, null,null]
I try to move object 3 after object 2 without delete "null case", but it's doesn't work. So I would like to iterate my arrayList from right to left and check if the value is not null and then move Object 3 behind object 2. I precise that I don't know the number of "null case" between object 2 and Object 3
I try to write this:
ArrayList<Type> subList = new ArrayList<Type>();
for (int i = 0; i < array.size(); i++) {
subList = array.get(i);
for (int j = subList.size(); j >=0 ; j--) {
if(subList.get(j)!=null) {
Collections.swap(subList, j, j-1);
}
}
}
edit:
solution 1: that works for my project
for(int i=0;i<subList.size();i++)
if(subList.get(i)!=null) {
for(int j=0;j<i;j++) {
if (subList.get(j)==null) {
Collections.swap(subList,i,j);
break;
}
}
}
}
solution 2 : copy in other arraylist
doesn't work for my project, don't know why
List<String> strings = Arrays.asList(new String[]{"A", null, "B"});
List<String> result = new ArrayList<String>();
for(String string : strings) {
if(string != null)
result.add(string);
}
for (int i = 0, remaining = strings.size() - result.size(); i < remaining; i++) {
result.add(null);
}
Update 2:
To swap between object with out create any new List , Use Collections.swap() ; Something like this:
public static void main(String[] args) {
ArrayList subList = new ArrayList();
subList.add("1");
subList.add("2");
subList.add(null);
subList.add(null);
subList.add("3");
for(int i=0;i<subList.size();i++)
if(subList.get(i)!=null) {
for(int j=0;j<i;j++) {
if (subList.get(j)==null) {
Collections.swap(subList,i,j);
break;
}
}
}
}
}
Update 1:
Try this :
public static void main(String[] args) {
ArrayList subList = new ArrayList();
subList.add("1");
subList.add("2");
subList.add(null);
subList.add(null);
subList.add("3");
subList=leftShift(subList);
}
public static ArrayList leftShift(ArrayList x){
ArrayList temp=new ArrayList();
int count=0;
for(Object t:x){
if(t!=null)
temp.add(t);
else
count++;
}
for (int i=0;i<count;i++)
temp.add(null);
return temp;
}
solution from top of my head, is not brilliant, but it will allow you to keep order
int nullIndex = -1;
for (int i = 0; i < list.size(); i++) {
if (nullIndex==-1 && list.get(i) == null) {
System.out.println("nullIndex ="+i);
nullIndex = i;
} else if (nullIndex >= 0 && list.get(i) != null) {
System.out.println("swap ="+i+" "+nullIndex);
list.set(nullIndex, list.get(i));
list.set(i, null);
i = nullIndex;
nullIndex=-1;
}
}
sorry i forgot you are using arraylist, you can do this simpler
int counter=0;
while(subList.contains(null)){
subList.remove(null);
counter++;
};
while(counter>0){
subList.add(null);
counter--;
}
I have a ArrayList: ArrayList<String> buffer = new ArrayList<String>();
How can I take duplicated values from ArrayList?
Example:
fsfs.txt
erwre.txt
wery.txt
wtrtr.txt
erwre.txt
qweq.txt
My attempts:
With cycles:
for(int i = 0; i < buffer.size(); i++) {
for(int j = i + 1; j < buffer.size(); j++) {
if( buffer.get(i).equals(buffer.get(j)) ) {
bufferTemp.add(j, buffer.toString() );
j--;
}
}
}
With iterator:
Iterator<String> i = buffer.iterator();
Iterator<String> j = buffer.iterator();
j.next();
while(i.hasNext() && j.hasNext()) {
if( i.next().equals(j.next() )
System.out.println(i.next());
}
Also I try to use Comparable, Comparator and other ways but it don't work.
You can create a Set passing the your list as a argument. Set will take care of duplicates.
private static List<String> list = new ArrayList<String>();
public static void main(String[] args) {
list.add("aaa.txt");
list.add("aaa.txt");
list.add("aaa.txt");
list.add("bbb.txt");
list.add("ccc.txt");
list.add("ccc.txt");
Set<String> set = new HashSet<String>(list);
System.out.println(set);
}
If I understand you correctly, you use Java and want to get the duplicates of an ArrayList.
If you use Strings, then you can just sort the List and compare in a loop the previous with the current element. Look at this (Java 7):
ArrayList<String> list = new ArrayList<>();
list.add("fsfs.txt");
list.add("erwre.txt");
list.add("wery.txt");
list.add("wtrtr.txt");
list.add("erwre.txt");
list.add("qweq.txt");
// Sort the list
Collections.sort(list);
// Test if List was sorted correctly
for(String s : list)
{
System.out.println(s);
}
System.out.println("\n*** Now try to get duplicates ***\n");
Iterator<String> listIt = list.iterator();
String prev = "";
boolean foundDuplicate = false;
while(listIt.hasNext())
{
String current = listIt.next();
if(current.equals(prev))
foundDuplicate = true;
else
foundDuplicate = false;
if(foundDuplicate)
{
// Duplicate found!
System.out.println(current);
}
prev = current;
}
Output should be:
erwre.txt
erwre.txt
fsfs.txt
qweq.txt
wery.txt
wtrtr.txt
*** Now try to get duplicates ***
erwre.txt
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));
}
}