Remove Data and Arraylist looping - java

I have a object with 3 variable (id(string), year(int), pay(double))
I have created an arraylist that contains object.
So now I need to sum the the pay if they have the same id and year and store it in a new array! is that possible?
ArrayList<Earning> temp = new ArrayList();
ArrayList<Earning> temp = new ArrayList();
double tempEarning = 0.0;
int count = 0;
for (int i = 0; i < weeklyEarnings.size(); i++) {
Earning e = weeklyEarnings.get(i);
String id = e.getId();
int year = e.getYear();
tempEarning = e.getEarning();
Earning e2 = weeklyEarnings.get(i + 1);
if (id.equalsIgnoreCase(e2.getId()) && year == e2.getYear()) {
tempEarning += e2.getEarning();
} else {
Earning tempEarn = new Earning();
tempEarn.setEarning(tempEarning);
tempEarn.setId(id);
tempEarn.setYear(year);
temp.add(tempEarn);
count++;
tempEarning = 0.0;
}
}
weeklyEarnings.clear();
weeklyEarnings = temp;
temp.clear();
Can someone Help me? Thanks a lot!

Try this:
HashMap<String, Earning> totalEarnings = new HashMap<String, Earning>();
for (Earning earning : weeklyEarnings) {
Earning tmpEarning = totalEarnings.get(earning.getId() + earning.getYear());
if (tmpEarning == null) {
tmpEarning = new Earning();
tmpEarning.setId(earning.getId());
tmpEarning.setYear(earning.getYear());
totalEarnings.put(earning.getId() + earning.getYear(), tmpEarning);
}
tmpEarning.setEarning(tmpEarning.getEarning() + earning.getEarning());
}
for (Earning earning : totalEarnings.values())
{
System.out.println(earning.getId() + ' ' + earning.getyear() + ' ' + earning.getEarning());
}

You can do it like this.
Iterate through the list.
Match each item in the list with one id.
If match found "Sum Pay".
Continue for each item in the list.

Related

Loop through multiple arraylists and get elements

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);
}
}
}

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.

Handling an Array in Java (two columns)

For instance suppose I have the following String
String S = "5,a\n" +
"6,b\n" +
"9,a";
The format is always the same - one digit, then comma, then one character and then line end character.
For looping each row in String I use
for(String a : S.split("\\n")){}
I want to learn the character with highest amount, when grouped by character. For Instance, there is only one "b", so value is 6; whereas "a" has two lines, so its value is 5 + 9 = 14. Since 14 is maximum here, I want to find out "a" and 14 and save them in variables.
You can do something like below :
public static void main (String[] args) throws java.lang.Exception
{
String S = "5,a\n" +
"6,b\n" +
"9,a";
String[] lines = S.split("\\n");
Map<String, Integer> map = new HashMap<String, Integer>();
for( String t : lines )
{
String[] e = t.split(",");
Integer digit = Integer.parseInt(e[0]);
String c = e[1];
if ( map.get(c) != null )
{
Integer val = map.get(c);
val += digit;
map.put( c, val );
}
else
{
map.put( c, digit );
}
}
int max = 0;
String maxKey = null;
for ( String k : map.keySet() )
{
if ( map.get(k) > max )
{
max = map.get(k);
maxKey = k;
}
}
System.out.println("The maximum key is : " + maxKey );
System.out.println("The maximum value is : " + max );
}
Output is :
The maximum key is : a
The maximum value is : 14
Use a HashMap to store each pair, with the letter as the key. If the entry doesn't exist, put the first number. If it exists, get the entry and add the number, and then put the sum.
import java.util.HashMap;
import java.util.Map;
public class ParseTest {
public static void main(String[] args) {
String S = "5,a\n" + "6,b\n" + "9,a";
String maxKey = null;
int maxVal = 0;
Map<String, Integer> sums = new HashMap<>();
for (String a : S.split("\\n")) {
String[] split = a.split(",");
int value = Integer.parseInt(split[0]);
String key = split[1];
if (sums.containsKey(key)) {
sums.put(key, sums.get(key) + value);
} else {
sums.put(key, value);
}
if (sums.get(key) > maxVal) {
maxVal = sums.get(key);
maxKey = key;
}
}
System.out.println("Max key: " + maxKey + ", Sum: " + maxVal);
}
}
After finishing my answer, I found that many similar answers have been posted out :). Anyway, my solution:
public static void main(String[] args) {
String S = "5,a\n6,b\n9,a";
Map<String, Integer> map = new HashMap<String, Integer>();
String highestAmountChar = "";
int highestAmount = 0;
for (String str : S.split("\\n")) {
String[] amountChar = str.split(",");
if (map.get(amountChar[1]) == null) {
map.put(amountChar[1], Integer.parseInt(amountChar[0]));
} else {
map.put(amountChar[1], map.get(amountChar[1]) + Integer.parseInt(amountChar[0]));
}
if (highestAmount < map.get(amountChar[1])) {
highestAmount = map.get(amountChar[1]);
highestAmountChar = amountChar[1];
}
}
System.out.println("The character " + highestAmountChar + " has highest amount " + highestAmount);
}
You could use something like this without using HashMap or any collection for that matter
import java.util.Arrays;
public class Test {
public static void main(String args[]) {
String S = "5,a\n" +
"6,b\n" +
"9,a";
// Separate the string by number and letter
String[] separated = S.split("\\n");
// Create a new array to store the letters only
char[] letters = new char[separated.length];
// Write the letter
for (int i = 0; i < letters.length; i++) {
letters[i] = separated[i].charAt(2);
}
// Sort them haha
Arrays.sort(letters);
// And now find out which letter is repeated most
// Store the first letter
char previous = letters[0];
// Make it the most repeated one for now
char mostRepeated = letters[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < letters.length; i++) {
// since the array is sorted if the actual letter is the same as the previous one then keep counting
if (letters[i] == previous)
count++;
else {
if (count > maxCount) {
mostRepeated = letters[i - 1];
maxCount = count;
}
previous = letters[i];
count = 1;
}
}
char answer = count > maxCount ? letters[letters.length-1] : mostRepeated;
// Once you get the letter now just add all the numbers that goes with it
int sum = 0;
for (String s:separated) {
if (s.charAt(2) == answer) {
sum += Character.getNumericValue(s.charAt(0));
}
}
// Print the result by printing the letter and it sum
}
}

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());

Add to list at certain index

I'm having a problem with some list manipulation. I take the user's input and search through it: if i find an "=" sign i assume that the string in front of it is the name of a variable , so on the line right above that variable i want to add a new string to the user's input (in this case it is called "tempVAR", doesn't really matter though). I've been trying to do this with StringBuilder but without any success , so i currently am trying to do it with ArrayLists but I am getting stuck at adding new elements to the list. Because of the way list.add(index,string) works , the elements to the right of what i am adding will always add +1 to their index. Is there a way to always know exactly what index i am looking for even after a random number of string has been added? Here is my code so far, if you run it you will see what i mean, instead of "tempVAR" or "tempVar1" being added above the name of the variable they will be added one or to positions in the wrong way.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
public class ToTestStuff {
static List<String> referenceList = new ArrayList<String>();
public static final String SEMICOLUMN = ";";
public static final String BLANK = " ";
public static final String EMPTY = "";
public static final String LEFT_CURLY = "{";
public static final char CARRIAGE_RETURN = '\r';
public static final String CR_STRING = "CARRIAGE_RETURN_AND_NEW_LINE";
public static final char NEW_LINE = '\n';
public static void main(String[] args) {
List<String> test = new ArrayList<String>();
String x = "AGE_X";
String y = "AGE_Y";
String z = "AGE_YEARS";
String t = "P_PERIOD";
String w = "T_VALID";
referenceList.add(x);
referenceList.add(y);
referenceList.add(z);
referenceList.add(t);
referenceList.add(w);
String text2 = " if ( AGE_YEARS > 35 ) {\r\n"
+ " varX = P_PERIOD ;\r\n"
+ " }\r\n"
+ " if ( AGE_YEARS < 35 ) {\r\n"
+ " varY = T_VALID ;\r\n"
+ " varZ = AGE_Y ;\r\n"
+ " varA = AGE_X ;\r\n"
+ " }";
detectEquals(text2);
}
public static String detectEquals(String text) {
String a = null;
// text = text.trim();
// text = TestSplitting.addDelimiters(text);
String[] newString = text.split(" ");
List<String> test = Arrays.asList(newString);
StringBuilder strBuilder = new StringBuilder();
HashMap<String, List<Integer>> signs = new HashMap<String, List<Integer>>();
HashMap<String, List<Integer>> references = new HashMap<String, List<Integer>>();
HashMap<Integer, Integer> indexesOfStringAndList = new HashMap<Integer, Integer>();
List<String> testList = new ArrayList<String>();
List<Integer> lastList = new ArrayList<Integer>();
List<Integer> indexList = new ArrayList<Integer>();
List<Integer> refList = new ArrayList<Integer>();
List<String> keysList = new ArrayList<String>();
List<List> minList = new ArrayList<List>();
String previous = null;
int index = 0;
Object obj = new Object();
List<Integer> referenceValueList = new ArrayList<Integer>();
List<Integer> indexPosition = new ArrayList<Integer>();
String b = null;
int indexOfa = 0;
// System.out.println("a----> " + test);
List<String> anotherList = new ArrayList(test);
for (int i = 0; i < anotherList.size(); i++) {
a = anotherList.get(i).trim();
index = strBuilder.length();// - a.length();
// index = i;
strBuilder.append(a); // "=", 3 - if, 14 - while, 36 , "=", 15
testList.add(a);
if (a.equals("if") || a.equals("=")) {
lastList.add(i);
indexOfa = i;
indexesOfStringAndList.put(index, indexOfa);
refList.add(index);
indexPosition.add(index);
if (signs.containsKey(a)) {
signs.get(a).add(index);
} else {
signs.put(a, refList);
}
refList = new ArrayList<Integer>();
}
if (referenceList.contains(a)) {
indexList.add(index);
if (references.containsKey(a)) {
references.get(a).add(index);
} else {
references.put(a, indexList);
}
indexList = new ArrayList<Integer>();
}
}
for (String k : references.keySet()) {
keysList.add(k);
referenceValueList = references.get(k);
obj = Collections.min(referenceValueList);
int is = (Integer) obj;
ArrayList xx = new ArrayList();
xx.add(new Integer(is));
xx.add(k);
minList.add(xx);
}
for (List q : minList) {
Integer v = (Integer) q.get(0);
String ref = (String) q.get(1);
int x = closest(v, indexPosition);
int lSize = anotherList.size();
int sizeVar = lSize - test.size();
int indexOfPx = 0;
int px = 0;
if (x != 0) {
px = indexesOfStringAndList.get(x) - 1;
} else {
px = indexesOfStringAndList.get(x);
}
if (px == 0) {
System.out.println("previous when x=0 " +anotherList.get(px+sizeVar));
anotherList.add(px, "tempVar1=\r\n");
} else {
previous = anotherList.get(px + sizeVar);
System.out.println("previous is---> " + previous + " at position " + anotherList.indexOf(previous));
anotherList.add(anotherList.indexOf(previous) - 1, "\r\ntempVAR=");
}
}
strBuilder.setLength(0);
for (int j = 0; j < anotherList.size(); j++) {
b = anotherList.get(j);
strBuilder.append(b);
}
String stream = strBuilder.toString();
// stream = stream.replaceAll(CR_STRING, CARRIAGE_RETURN + EMPTY + NEW_LINE);
System.out.println("after ----> " + stream);
return stream;
}
public static int closest(int of, List<Integer> in) {
int min = Integer.MAX_VALUE;
int closest = of;
for (int v : in) {
final int diff = Math.abs(v - of);
if (diff < min) {
min = diff;
closest = v;
}
}
return closest;
}
}
I've mapped the positions of the "=" and "if" to their positions in the StringBuilder, but these are remnants from when i was trying to use a stringBuilder to do what i said above.
I have been struggling with this for a few days now and still haven't managed to do what i need, i am not sure where i am going wrong. At the moment i am hellbent on making this work as it is (with either lists or string builder) after which , if there is a better way i will look into that and adapt this accordingly.
The addDelimiters() method is a method i created to avoid writing the string as you see it in "String text2" but i took that out for this because it would only clutter my already chaotic code even more :), i don't think it has any relevance to why what i am trying to do is not working.
TLDR: at the line above front of every varX or varY or other "var" i would like to be able to add a string to the list but i think my logic in getting the variable names or in adding to the list is wrong.
I think we both know that your code is messed up and that you need many more abstractions to make it better. But you could make it work by maintaining an offset variable, lets say "int offset". Each time you insert a string after the initial pass you increment it, and when you access the list you use it, "list.get(index+offset);". Read up on Abstract syntax trees. , which are a great way to parse and manipulate languages.

Categories