Loop through multiple arraylists and get elements - java

public static void main(String[] args)
{
loadDependencies ld = new loadDependencies();
List<String> ls = ld.loadDependenciesFromPom();
getAvailableHigherVersions ah = new getAvailableHigherVersions();
List<List<String>> vl = ah.versionListOnly();
String previousVersion=null;
for ( int a=0; a<vl.size();a++) {
List<String> tmp = vl.get(a);
for(int i=0; i<ls.size();i++){
String firstE = ls.get(i);
for(int j=0;j<tmp.size();j++) {
if (i==0 && j==0){
//xu.versionUpdate(previousVersion, tmp.get(j));
//String previousVersiontt = ls.get(i);
System.out.println(firstE + "----" + tmp.get(j));
}
/*xu.versionUpdate(previousVersion, tmp.get(j));
previousVersion=tmp.get(j);*/
//System.out.println(previousVersion+"-"+tmp.get(j));
// previousVersion = tmp.get(j);
}
}
}
}
"ls" is a String list. It contains like this
[1,4,5,7]
"vl"is a List of string list. It contains like this
[[1.5,1.6,1.7],[4.1,4.2,4.3],[5.1,5.2],[7.1,7.4]]
what I need to do is first take the 1st element of ls list
1
then i need to get the first element in the vl list
[1.5,1.6,1.7]
then output should be
[1,1.5]
then the next output would be
[1.5,1.6]
likewise iterate through the array.
Then next take the 2nd element of ls
4
then it should go like 4,4.1 then 4.1,4.2 likewise until the ls is empty.
I tried above code but some times it iterate multiple times. Any hint to fix this issue?

So if I understood well, you want something like this:
for (int a = 0; a < ls.size(); a++)
{
// Get first element
String firstE = ls.get(a);
// Get corresponding vl elements
List<String> vls = vl.get(a);
// Now print the elements
// The first element of vl should be preceeded by the corresponding element in ls
// The others by the predecessor in the same array
for (int b = 0; b < vls.size(); b++)
{
System.out.print("[");
if (b == 0)
System.out.print(firstE);
else
System.out.print(vls.get(b - 1));
System.out.println(", " + vls.get(b) + "]");
}
}

for(int i=0;i<ls.size();i++){
List<String> tmp = vl.get(i);
System.out.println(ls.get(i)+" "+temp.get(0));
for(int j=1;j<tem.size()-1;j++){
System.out.println(temp.get(j)+" "+temp.get(j+1));
}
}

for ( int a=0; a<vl.size();a++) {
List<String> tmp = vl.get(a);
String firstE = ls.get(a);
for (int j = 0; j < tmp.size(); j++) {
if (j == 0) {
//xu.versionUpdate(previousVersion, tmp.get(j));
//String previousVersiontt = ls.get(i);
System.out.println(firstE + "----" + tmp.get(j));
}
/*xu.versionUpdate(previousVersion, tmp.get(j));
previousVersion=tmp.get(j);*/
//System.out.println(previousVersion+"-"+tmp.get(j));
// previousVersion = tmp.get(j);
}
}
}

Related

Java How to get start and end of an element in an ArrayList

I have some dynamic values in an ArrayList
ClassnameOne <!----Begin---->
Classnametwo <!----Begin---->
Classnamethree <!----Begin---->
Classnamethree <!----End---->
Classnametwo <!----End--->
ClassnameOne <!----End---->
What I want to do is to get the beginning occurrence of an element and when it ends. So for example ClassnameOne would be 5, Classnametwo would be 3.
This is what I have done so far:
ArrayList<String> one = new ArrayList<String>();
for (int i = 0; i < one.size(); i++) {
if(one.get(i).contains("<!----End---->") && one.get(i).equals(one.get(i+1))) {
break;
} else {
count++;
System.out.println(one.get(i));
}
System.out.println(count);
}
This doesn't give the right answer. Can you please help?
ArrayList<String> one = new ArrayList<String>();
for (int starti = 0; starti < one.size(); ++starti) {
String[] words = one.get(starti).split(" ", 2);
if (words[1].equals("<!----Begin---->")) {
int n = 0;
String sought = words[0] + " " + "<!----End---->";
for (int endi = starti + 1; endi < one.size(); ++endi) {
if (one.get(endi).equals(sought) {
n = endi - starti;
break;
}
}
System.out.printf("%s at %d covers %d lines.%n", words[0], starti, n);
}
}
Assuming that the names do not repeat, otherwise a stack (or such) would to be needed.

Method to do compare and change single characters in a string

I need to do a method to check two string for example bod and bot or crab and rab. The method needs to print out what the user must do in order to make them equal. For example in bod and bot it will print "replace,2,d in the string". I used this code which seems to work.
if(a.length()==b.length()){
int i;
for(i=0; i<=a.length(); i++){
if(a.charAt(i)!=b.charAt(i)){
return "replace,"+ i + "," + b.charAt(i);
}
}
}
But I am having troubles if the two string are not equal in size. I use this but it doesn't work because one of the strings is bigger.
int aS = a.length();
int bS = b.length();
if(bS - aS == 1){
int i;
for(i=0; i<=b.length(); i++){
if(b.charAt(i)!=a.charAt(i)){
return "remove," + i;
}
}
}
Can you guys give me a suggestion what method I can use to check which is the extra letter or vice versa a letter I can add and then return a string saying either to remove a character or add an extra one. Thank you
Maybe something like this?
public ArrayList<String> createConversionList(String primary, String secondary){
//Determine which string is shorter.
String shorter;
String longer;
boolean primaryIsShorter = false;
if (primary.length() >= secondary.length()){
longer = primary;
shorter = secondary;
} else{
longer = secondary;
shorter = primary;
primaryIsShorter = true;
}
//Fills an array with all the character positions that differ between the
//two strings, using the shorter string as the base.
int[] posOfCharsToChange = new int[shorter.length()];
for(int i = 0; i < shorter.length(); i++){
if(shorter.charAt(i) != longer.charAt(i)){
posOfCharsToChange[i] = i;
} else{
posOfCharsToChange[i] = -1;
}
}
//Adds to an ArrayList all of the "Replace" strings.
ArrayList<String> conversionList = new ArrayList();
for(int pos: posOfCharsToChange){
if(pos != -1){
String s = "Replace " + secondary.charAt(pos) + " with " + primary.charAt(pos) + ". \n";
conversionList.add(s);
}
}
//Depending on which string was bigger, either adds "Add" or "Remove"
//strings to the ArrayList. If the strings were the same size, does
//nothing.
if(primary.length() != secondary.length()){
if(primaryIsShorter){
for(int i = primary.length(); i < secondary.length(); i++){
String s = "Remove " + secondary.charAt(i) + ". \n";
conversionList.add(s);
}
}
else{
for(int i = secondary.length(); i < primary.length(); i++){
String s = "Add " + primary.charAt(i) + ". \n";
conversionList.add(s);
}
}
}
return conversionList;
}
My Approach works as follows
1) We take the smaller string and put all its contents in an arraylist
2) We take the bigger string and put its contents in the arraylist only if its not present in the arraylist
3) The last character in the arraylist must be removed from the bigger string to make them equal
Ex 1:
a = rab
b = crab
1) arraylist = rab -> contents of a added
2) arraylist = rabc -> only unique content of b is added
Ex 2:
a = crab
b = rab
1) arraylist = rab
2) arraylist = rabc
similarly if the positions are in the middle or not at start ,
ex : a = racb
b = rab
1) arraylist = rab
2) arraylist = rabc
public class Replace {
public static void main(String args[]) {
int p = 0, j = 0;
String a = "rab";
String b = "crab";
if (b.length() < a.length()) {
ArrayList al = new ArrayList();
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String a");
} else {
ArrayList al = new ArrayList();
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String b");
}
}
}
Note - The program only works under your given contraints that strings only differ in one character and the ordering of both the strings is not different if we remove or add that charcter.

copying elements of an arraylist to another array list eliminating redundancy in the 2nd arraylist using Java

I would like to create a code that will help me copy elements from the 'allWords' ArrayList to the 'distinctWords'. but his time in the distinct words ArrayList I want a word to appear just one, eliminating redundancy in the "distinctWords' ArrayList.
this is the code that I have come up with and I am getting no output.
import java.util.ArrayList;
public class copyElements {
static ArrayList<String> distinctWords = new ArrayList<String> ();
static ArrayList<String> allWords = new ArrayList<String> ();
static int allWordsCount = 0;
static int distinctWordsCount;
static int tracker;
public static void main(String[] args) {
allWords.add("you");
allWords.add("want");
allWords.add("to");
allWords.add("go");
allWords.add("to");
allWords.add("dubai");
allWords.add("and");
allWords.add("you");
allWords.add("also");
allWords.add("want");
allWords.add("to");
allWords.add("go");
allWords.add("to");
allWords.add("seychelles");
//printing all items in the 'allwords' arraylist
//System.out.println("CONTENTS OF 'ALL WORDS' ARRAYLIST : ");
distinctWords.add(0,allWords.get(0));
distinctWordsCount = 1;
int i = 1;
for(int j = 1; j <= distinctWords.size(); j++){
if(i < allWords.size()){
tracker = 0;
if (tracker == j){
distinctWords.add(j, allWords.get(i));
System.out.println("\t\t\t" + distinctWords.get(j));
distinctWordsCount ++;
i++;
} else
if (tracker != j){
if(allWords.get(i) != distinctWords.get(tracker)){
//distinctWords.add(allWords.get(i));
//distinctWordsCount ++;
tracker++;
}
else
if(allWords.get(i) == distinctWords.get(tracker)){
i++;
}
//System.out.println("CONTENTS OF 'ALL WORDS' ARRAYLIST : ");
//System.out.println("\t\t\t" + distinctWords.get(j));
}
}
//System.out.println("\t\t\t" + distinctWords.get(j));
}
//System.out.println("\n\nTHE NUMBER OF ITEMS IN THE 'ALLWORDS' ARRAYLIST IS : " + allWords.size());
//System.out.println("\n\nTHE NUMBER OF ITEMS IN THE 'DISTINCTWORDS' ARRAYLIST IS : " + allWords.size());
System.out.println("\n\nITEMS IN THE 'DISTINCTWORDS' ARRAYLIST ARE : " + distinctWords.size());
}
}
How about the following code:
for (int i = 0, size = allWords.size(); i < size; i++)
{
String word = allWords.get(i);
// add the word if it is not in distinctWords
if (!distinctWords.contains(word))
{
distinctWords.add(word);
}
}
If you don't care about the order of the words, then you could use a Set as suggested.
Set<String> distinctSet = new HashSet<String>(allWords);
// if you want the set put into your other arrayList
distinctWords.addAll(distinctSet);
//al1 and al2 are ArrayList<Object>
for(Object obj:al1){
if(!al2.contains(obj))
al2.add(obj);
}
I think this can give you a set of all distinct words.
Set<String> distinctWords = new HashSet<>(allWords);
If you do need an array, you can simple do this:
ArrayList<String> distinctWordsArr = new ArrayList<>(distinctWords);

sub arraylist's size isn't correct

After hard searchig I still haven't found the proper answer for my question and there is it:
I have to write a java program that enters an array of strings and finds in it the largest sequence of equal elements. If several sequences have the same longest length, the program should print the leftmost of them. The input strings are given as a single line, separated by a space.
For example:
if the input is: "hi yes yes yes bye",
the output should be: "yes yes yes".
And there is my source code:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
ArrayList<ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
ArrayList<String> stringsSequences = new ArrayList<String>();
stringsSequences.add(strings[0]);
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
stringsSequences.add(strings[i]);
} else {
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
stringsSequences.add(strings[i]);
//ystem.out.println("\n" + stringsSequences);
}
if(i == strings.length - 1) {
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
System.out.println(stringsSequences + " " + stringsSequences.size());
}
}
System.out.println(stringsSequencesCollection.size());
System.out.println(stringsSequencesCollection.get(2).size());
System.out.println();
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
ArrayList<String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(String.join(" ", stringsSequencesCollection.get(index)));
I think it should be work correct but there is a problem - the sub array list's count isn't correct: All the sub arrayList's size is 1 and for this reason the output is not correct. I don't understand what is the reason for this. If anybody can help me to fix the code I will be gratefull!
I think it is fairly straight forward just keep track of a max sequence length as you go through the array building sequences.
String input = "hi yes yes yes bye";
String sa[] = input.split(" ");
int maxseqlen = 1;
String last_sample = sa[0];
String longest_seq = last_sample;
int seqlen = 1;
String seq = last_sample;
for (int i = 1; i < sa.length; i++) {
String sample = sa[i];
if (sample.equals(last_sample)) {
seqlen++;
seq += " " + sample;
if (seqlen > maxseqlen) {
longest_seq = seq;
maxseqlen = seqlen;
}
} else {
seqlen = 1;
seq = sample;
}
last_sample = sample;
}
System.out.println("longest_seq = " + longest_seq);
Lots of issues.
First of all, when dealing with the last string of the list you are not actually printing it before clearing it. Should be:
if(i == strings.length - 1)
//...
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequences.clear();
This is the error in the output.
Secondly, and most importantly, when you do stringsSequencesCollection.add you are adding an OBJECT, i.e. a reference to the collection. When after you do stringsSequences.clear(), you empty the collection you just added too (this is because it's not making a copy, but keeping a reference!). You can verify this by printing stringsSequencesCollection after the first loop finishes: it will contain 3 empty lists.
So how do we do this? First of all, we need a more appropriate data structure. We are going to use a Map that, for each string, contains the length of its longest sequence. Since we want to manage ties too, we'll also have another map that for each string stores the leftmost ending position of the longest sequence:
Map<String, Integer> lengths= new HashMap<>();
Map<String, Integer> indexes= new HashMap<>();
String[] split = input.split(" ");
lengths.put(split[0], 1);
indexes.put(split[0], 0);
int currentLength = 1;
int maxLength = 1;
for (int i = 1; i<split.length; i++) {
String s = split[i];
if (s.equals(split[i-1])) {
currentLength++;
}
else {
currentLength = 1;
}
int oldLength = lengths.getOrDefault(s, 0);
if (currentLength > oldLength) {
lengths.put(s, currentLength);
indexes.put(s, i);
}
maxLength = Math.max(maxLength, currentLength);
}
//At this point, youll have in lengths a map from string -> maxSeqLengt, and in indexes a map from string -> indexes for the leftmost ending index of the longest sequence. Now we need to reason on those!
Now we can just scan for the strings with the longest sequences:
//Find all strings with equal maximal length sequences
Set<String> longestStrings = new HashSet<>();
for (Map.Entry<String, Integer> e: lengths.entrySet()) {
if (e.value == maxLength) {
longestStrings.add(e.key);
}
}
//Of those, search the one with minimal index
int minIndex = input.length();
String bestString = null;
for (String s: longestStrings) {
int index = indexes.get(s);
if (index < minIndex) {
bestString = s;
}
}
System.out.println(bestString);
Below code results in output as you expected:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
List <ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
List <String> stringsSequences = new ArrayList<String>();
//stringsSequences.add(strings[0]);
boolean flag = false;
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
if(flag == false){
stringsSequences.add(strings[i]);
flag= true;
}
stringsSequences.add(strings[i]);
}
}
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
List <String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(stringsSequences.toString());

Swapping string position in Arraylist java

I have a sentence: Humpty Dumpty sat on a wall.
I want the strings to swap positions such that : Dumpty Humpty on sat wall a.
So the code that I wrote is following :
import java.util.*;
public class Swap{
public static void main(String []args) {
ArrayList<String> sentence = new ArrayList<String>();
sentence.add("Humpty");
sentence.add("Dumpty");
sentence.add("sat");
sentence.add("on");
sentence.add("a");
sentence.add("wall");
int size = sentence.size() ; // for finding size of array list
int numb ;
if(size%2 == 0) {
numb = 1;
}
else {
numb = 0;
}
ArrayList<String> newSentence = new ArrayList<String>();
if(numb == 1) {
for(int i = 0; i <= size ; i = i+2) {
String item = sentence.get(i);
newSentence.add(i+1, item);
}
for(int i = 1; i<=size ; i = i+2) {
String item2 = sentence.get(i);
newSentence.add(i-1, item2);
}
System.out.println(newSentence);
}
else {
System.out.println(sentence);
}
}
}
The code is compiling correct but when I run it, its giving an error.
What i understand of this is that I am adding strings to the array list leaving positions in between. Like adding at position 3 without filling position 2 first. How do I overcome this problem ?
You're correct about your problem - you're trying to insert an element into index 1 before inserting an element at all (at index 0), and you get an IndexOutOfBoundsException.
If you want to use your existing code to achieve this task, simply have just one loop as such:
if(numb == 1) {
for(int i = 0; i < size-1 ; i = i+2) {
String item = sentence.get(i+1);
newSentence.add(i, item);
item = sentence.get(i);
newSentence.add(i+1, item);
}
}
If you want to be a bit more sophisticated a use Java's built-in functions, you can use swap:
for(int i = 0; i < size-1 ; i = i+2) {
Collections.swap(sentence, i, i+1);
}
System.out.println(sentence);
You can initilize newSentence using:
ArrayList<String> newSentence = new ArrayList<String>(Collections.nCopies(size, ""));
This will let you access/skip any position in between 0 and size. So you can keep your rest of the code as it is.
just remember all index are being populated with empty String here.
That is because:
for(int i = 0; i <= size ; i = i+2) {
String item = sentence.get(i);
newSentence.add(i+1, item);//Here you will face java.lang.IndexOutOfBoundsException
}
for(int i = 1; i<=size ; i = i+2) {
String item2 = sentence.get(i);
newSentence.add(i-1, item2);//Here you will face java.lang.IndexOutOfBoundsException
}
instead of this, try following code:
if(numb == 1) {
for(int i = 0; i < size-1 ; i +=2) {
Collections.swap(sentence, i, i+1);
}
}

Categories