Modify elements of an ArrayList - java

For the below code, I was hoping that elements of my arraylist would be modified but its not. How can I modify the elements
public class Main {
public static void main(String args[]){
ArrayList<String> aList = new ArrayList<>();
aList .add("aa");
aList .add("bb");
aList .add("cc");
new Main().modifyList(aList );
for(String s: aList ){
System.out.println(s);
}
}
public void modifyList(ArrayList<String> aList ){
for(String s: aList){
System.out.println(s);
s = s + "ss";
}
}
}
Its printing
aa
bb
cc
aa
bb
cc
Expected output
aa
bb
cc
aass
bbss
ccss

public void modifyList(ArrayList<String> aList ){
for(String s: aList){
System.out.println(s);
s = s + "ss";
}
}
Strings are immutable. So when you change s you are creating a new object that is different than the one in the ArrayList.
So you need to iterate over the array and replace the old value with the new using the set method.
for (int i = 0; i < alist.size(); i++) {
String s = aList.get(i) + "ss";
aList.set(i, s);
}
To simply append the changes do the following:
int len = alist.size();
for (int i = 0; i < len; i++) {
String s = aList.get(i) + "ss";
aList.add(s);
}
Prints
aa bb cc aass bbss ccss

Here is the problem, the variable s is unused and visible only in the scope of the for-loop:
for (String s: aList) {
System.out.println(s);
s = s + "ss"; // the variable 's' is unused
}
Either use List::set to replace the current value:
for (int i=0; i<aList.size(); i++) {
String s = aList.get(i);
System.out.println(s);
aList.set(i, s + "ss");
}
... or use the advantage of java-stream as of java-8 and map the list to a new one:
List<String> newList = aList.stream()
.map(s -> s + "ss")
.collect(Collectors.toList());

s = s + "ss" only updates the local variable s, it doesn't update the list.
If you want to update elements in a list, use a ListIterator and the set() method:
public static void modifyList(List<String> aList) {
for (ListIterator<String> iter = aList.listIterator(); iter.hasNext(); ) {
String s = iter.next();
s = s + "ss";
iter.set(s); // replace element in the list with new value
}
}
In Java 8+, you can use a lambda expression with the replaceAll() method:
public static void modifyList(List<String> aList) {
aList.replaceAll(s -> s + "ss");
}
Both will perform well even if the list doesn't handle random access well, e.g. if the list is a LinkedList.
Test
public static void main(String[] args) {
List<String> aList = new ArrayList<>(Arrays.asList("aa", "bb", "cc"));
modifyList(aList);
System.out.println(aList);
}
Output
[aass, bbss, ccss]

In order to solve this, you need to update each element as follows:
public void modifyList(ArrayList<String> aList){
for(int i = 0; i < aList.size(); i++){
String s = aList.get(i);
aList.set(i, s+"ss");
}
}

Related

How to split strings of list into string array

I have a list that contains ("One.two.three", "one.two.four"). I want to save then in a string array as
One
two
three
one
two
four
What is the logic behind it?
You should be using java 8 to run this code. Just take those strings and split them on "."
split method of java need regex so to match "." you need "\.".Then transform array to list, then add words to list.
public static void main(String[] args) {
List<String> words = new ArrayList<String>();
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("one.two.four");
list.stream().forEach(str -> {
words.addAll(Arrays.asList(str.split("\\.")));
});
System.out.println(words.toString());
//output : [One, two, three, one, two, four]
}
For java 8+, you can use flatmap as -
String[] words = list.stream().flatMap(str -> Arrays.stream(str.split("\\."))).toArray(String[]::new);
If you are talking about the static arrays it is important to know array size to avoid "index is out of bounds" exception.
This way, I provide the solution that counts the number of words and then creates output s array to save every word.
We can use the String.split() function to get the single words we adding to output array:
String[] a = {"One.two.three", "one.two.four"};
int count = 0;
for (int i = 0; i < a.length; i++) { //skip this loop if you know the wanted array size
count += a[i].split("\\.").length;
}
String[] s = new String[count];
int k = 0;
for (int i = 0; i < a.length; i++) {
String[] b = a[i].split("\\.");
for (int j = 0; j < b.length; j++) {
s[k++] = b[j];
}
}
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
Try this.
FOR JAVA 1.8+
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
list.forEach(string -> {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
});
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
UPTO JAVA 1.7
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
for (String string : list) {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
}
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
If you are below Java 8 you can use this snippet:
public class Main {
public static void main(String[] args) throws Exception {
List<String> originalList = new ArrayList();
List<String> finalList = new ArrayList();
originalList.add("One.two.three");
originalList.add("One.two.four");
for(String myString : originalList) {
//The \\ is to scape the dot
finalList.addAll(Arrays.asList(myString.split("\\.")));
}
//Creates an array from the list
String[] theArray = finalList.toArray(new String[finalList.size()]);
}
}
Finally, theArray will contain:
[One, two, three, one, two, four]
Take a look at the docs about splitting an string into parts

Remove the duplicate pair from List

i was working on one issue i am not getting the expected output.
A String array “F1” has got names of Facebook users and their friend association.
For example, if we write: U1,U2 it implies that U1 is a friend of U2. This also implies that U2 is a friend of U1.
Write a program which will read “F1” and remove duplicates and write all the unique pairs to “F2”.
But, before removing duplicates
Input String => ["U1,U2","U3,U4","U2,U1","U1,U5"]
Output String => ["U1,U2","U1,U5","U3,U4"]
public static void main(String args[]) {
List test = new ArrayList();
List<String> list = new ArrayList();
list.add("U1,U2");
list.add("U3,U4");
list.add("U2,U1");
list.add("U1,U5");
Collections.sort(list);
for (String str : list) {
String i1 = str.substring(0, 2);
String i2 = str.substring(3, 5);
System.out.println(i2);
if (!i1.equals(i2)) {
test.add(str);
}
if (!(str.contains(i1) && str.contains(i2)) || !(str.contains(i2) && str.contains(i1))) {
System.out.println(str);
}
}
}
}
This is how it is done ;)
class Program
{
static void Main(string[] args)
{
List<string> test = new List<String>();
List<String> list = new List<String>();
List<String> list1 = new List<String>();
List<String> outputList = new List<String>();
list.Add("MARY,JOE");
list.Add("A,B");
list.Add("B, A");
list.Add("3");
list.Add("3");
list.Add("3,3");
list.Add("3,3");
var aa = compareFriends(list);
Console.ReadLine();
}
public static List<string> compareFriends(List<string> allfrndsList)
{
var frndsList = allfrndsList.Distinct().ToList();
var outputList = new List<string>(frndsList);
var listCount = frndsList.Count();
var startIndex = 1;
foreach (var friend in frndsList)
{
friend.Replace(" ","");
var str = friend.Split(',');
var i1 = str.FirstOrDefault();
var i2 = str.LastOrDefault();
for (var index = startIndex; index < listCount; index++)
{
var innerStr = frndsList[index].Replace(" ","").Split(',');
var temp1 = innerStr.FirstOrDefault();
var temp2 = innerStr.LastOrDefault();
if (innerStr.Length != 1 && str.Length!=1)
{
if (i1.Equals(temp2) && i2.Equals(temp1))
{
outputList.Remove(friend);
}
}
}
startIndex++;
}
return outputList;
}
}
Make a key of every pair, where the first value is smaller than the second value. ("U1,U2" and "U2,U2" will both result in "U1,U2"). Add these keys to a Set (a set removes duplicates for you). In the end you have a unique set of friend relationships.
Set<String> f2=new HashSet<>();
for (String str : list) {
String[] users=str.split(",");
String i1 = users[0];
String i2 = users[1];
String key=i1.compareTo(i2)>0?i2+","+i1:i1+","+i2;
f2.add(key);
}
System.out.println(f2);
List test = new ArrayList();
List<String> list = new ArrayList();
list.add("JOE,MARY");
list.add("A,B");
Set<String> f2 = new HashSet<>();
for (String str : list) {
String[] users = str.split(",");
String i1 = users[0];
String i2 = users[1];
String key = i1.compareTo(i2) > 0 ? i2 + "," + i1 : i1 + "," + i2;
f2.add(key);
}
Iterator val = f2.iterator();
while (val.hasNext()) {
test.add(val.next());
}
Collections.sort(test);
System.out.println("test" + test);
In C#:
class Program
{
static void Main(string[] args)
{
List<string> list1 = new List<string>();
list1.Add("U1,U2");
list1.Add("U3,U4");
list1.Add("U2,U1");
list1.Add("U1,U5");
List<string> list2 = new List<string>();
foreach (string s in list1)
{
var list3 = s.Split(',');
Array.Sort(list3);
list2.Add(list3.FirstOrDefault() + ',' + list3.LastOrDefault());
}
list2.Sort();
var list4 = list2.Distinct().ToList();
Console.WriteLine("Input string:");
foreach (string s in list1)
Console.WriteLine(s);
Console.WriteLine("\nOutput string:");
foreach (string s in list4)
Console.WriteLine(s);
Console.Read();
}
}
We can look at it as an undirected graph
You have to remove duplicate paths
Since it's undirected, "U1, U2" and "U2, U1" are the same path
Therefore, if path U1, U2 already exist, then U2, U1 is duplicate, so remove it.
Any of the suggestions in the comments will yield a viable solution
In Python :
f1 = [("U1", "U2"), ("U3", "U4"), ("U1", "U5"), ("U2", "U1"), ("U3", "U4")]
nw_lst = []
f1 = list(set(filter(lambda x: x[0] != x[1], f1)))
for i in f1:
val1 = int(i[0][1]) + int(i[1][1])
for j in range(f1.index(i) + 1, len(f1)):
val2 = int(f1[j][0][1]) + int(f1[j][1][1])
if val1 == val2:
nw_lst.append(f1[j])
f2 = set(f1).difference(set(nw_lst))
for i in f2:
print(f"{i[0]} , {i[1]}")
The below solution is written in JavaScript.
// Insert Multidimensional Array
arr = [["U1","U2"], ["U3","U4"], ["U1","U5"], ["U1","U2"], ["U3","U4"]];
function friendsArrRemover(arr) {
var a = [];
var itemsFoundArr = {};
for(var i = 0, l = arr.length; i < l; i++) {
var stringified = JSON.stringify(arr[i]);
if(itemsFoundArr[stringified]) { continue; }
a.push(arr[i]);
itemsFoundArr[stringified] = true;
}
return a;
}
friendsArrRemover(arr);
public class Main
{
public static void main(String[] args) {
String a = "ABC";
String b = "BC";
String op1="";
String op2="";
for (int i = 0; i < a.length(); i++) {
if(!b.contains(""+a.charAt(i))){
op1+=a.charAt(i);
}
}
for (int i = 0; i < b.length(); i++) {
if(!a.contains(""+b.charAt(i))){
op2+=b.charAt(i);
}
}
System.out.println(op1);
System.out.println(op2);
}
}
Below is the answer to remove the duplicate pair from list using C#.
protected void Page_Load(object sender, EventArgs e)
{
List<string> list = new List<string>();
list.Add("U1,U2");
list.Add("U3,U4");
list.Add("U2,U1");
list.Add("U1,U5");
var result=compareFriends(list);
foreach (string value in result)
{
Response.Write(value + "");
}
}
public static List<string> compareFriends(List<string> frndsList)
{
List<string> F2 = new List<string>();
frndsList.Sort();
foreach (string str in frndsList)
{
string s1 = str.Substring(0, 2);
string s2 = str.Substring(3, 2);
string key;
if (s1.CompareTo(s2)>0)
{
key = s2 + "," + s1;
}
else
{
key = s1 + "," + s2;
}
F2.Add(key);
}
var result = F2.Distinct();
return result.ToList();
}

How can I combine elements at the same index from separate lists?

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

How can I get duplicate values from ArrayList?

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

compare list and array

I need to compare the value from List with the value from array.
I wrote the following:
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
for (int i = 0; i < l.size(); i++){
v = "";
s = "";
//System.out.println(l.get(i));
for (int j = 0; j < arr.length; j++){
if (l.get(i).equals(arr[j])){
s = i + "";
}else{
s = arr[i];
}
v = v + s + ",";
}
System.out.println(v);
}
}
}
I obtain the following
0,test,test,
c,c,1
but I need the result like this:
0, c, 1,
Looking at your expected result I guess the requirement like that:
for each element in the array, check if it is on the list. If it is on the list, print the index from the list for this element, otherwise print the element itself. So the algorithm should do:
array[0] = "test" -> found at index 0 -> print "0"
array[1] = "c" -> not found -> print "c"
array[2] = "b" -> found at index 1 -> print "1"
The outer loop should iterate over the array. Then, for each array item, iterate over the list until you find the same element. For a first draft, don't collect the output in a string but print it immediatly. You can create the string when the algorithm works as expected.
You have six iterations, each of which inserts something into the output.
You want three iterations, each of which checks for membership in the first list. You can do that with the List.contains() method. (If the list were long, you might want to consider using a Set instead of a List, to allow checking set membership more quickly.)
How about this:
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
int pointer = 0;
for (int i = 0; i < l.size(); i++){
//System.out.println(l.get(i));
for (; pointer < arr.length;){
if (l.get(i).equals(arr[pointer])){
s = i + "";
v = v + s + ",";
pointer++;
break;
}else{
s = arr[i];
}
pointer++;
v = v + s + ",";
}
}
System.out.println(v);
}
Try to break things down to their high level steps.
For each string in the array
find its place in the list
if the item is in the list
print its position
else
print the missing string
print a common and space
Once you have this you can spot that find its place in the list could be a method that returns the place in the list or -1 if it isn't in the list. Here's what I made (might have renamed a few things and used a StringBuilder but you can ignore that for the moment).
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(final String[] args) {
final List<String> listToSeach = new ArrayList<String>();
listToSeach.add("test");
listToSeach.add("b");
final String[] arrayElementsToFind = { "test", "c", "b" };
final StringBuilder output = new StringBuilder();
for (final String string : arrayElementsToFind) {
final int firstIndex = findFirstIndex(listToSeach, string);
if (firstIndex > -1) {
output.append(firstIndex);
} else {
output.append(string);
}
output.append(", ");
}
System.out.println(output);
}
private static int findFirstIndex(final List<String> list,
final String element) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(element)) {
return i;
}
}
return -1;
}
}
Well I suggest this:
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String[] arr = {"test", "c", "b"};
for(int i=0;i<arr.length;++i){
if(l.contains(arr[i]))
s = ""+l.indexOf(arr[i]);
else
s = arr[i];
v = v + s + ",";
}
If got what you saying correct,I think this is less verbose

Categories

Resources