Replace values in a list - java

I have a list with two values like below:
at 0: yesnonoyesyes
at 1: yes=1;no=0
I need to replace value in'0' with the values after '=' in '1'.
I have written below code:
Can somebody please help
List<String> list = new ArrayList<>();
list.add("truetruefalsefalsefalse");
list.add("true=Ja;false=Nein");
String string0 = list.get(0);
String string1 = list.get(1);
String[] split = string1.split(";");
String replace = new String();
for (String string : split) {
if (string0.contains(StringUtils.substringBefore(string, "="))) {
replace = string0.replace(StringUtils.substringBefore(string, "="), StringUtils.substringAfter(string, "="));
}
}

After replacement you are not assigning the value back to list. That might be the issue.
Please have a look at the below sample implementation of your program.
import java.util.ArrayList;
import java.util.List;
public class ReplaceValues{
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("truetruefalsefalsefalse");
list.add("true=Ja;false=Nein");
String[] split = list.get(0).split(";");
for (String string : split) {
String combination[] = string.split("=");
list.set(0, list.get(0).replaceAll(combination[0], combination[1]));
}
for(String item:list){
System.out.println(item);
}
}
}
Output:
JaJaNeinNeinNein
true=Ja;false=Nein
Note: This will not work if you have overlapping strings eg.
true=ja
ue=t
As it will replace the ue again with t and overall result will be broken.
That's need to be handled saperatly.

Related

How to replace a string starting with a letter in Java

I want to create a method that print out the elements in ArrayList.
If the String start with a, e, i, o or u, instead of printing the String, it should print Buzz.
I am trying this way. But it isn't work.
ArrayList<String> names = new ArrayList<>();
names.add("Harry");
names.add("Kathy");
ArrayList<String> replaceArray = new ArrayList<>();
String buzzReplace[] ={"a","e","i","o","u"};
for(String value:names)
{
if(value.startsWith(buzzReplace))
{
replaceArray = names.replaceAll(value,"Buzz");
}
System.out.println(replaceArray.get(value));
}
I found a simply solution :
for (String name: names) {
for (String vowel: buzzReplace) {
if (name.startsWith(vowel)) {
name = "buzz";
break;
}
}
System.out.println(name);
}
if(value.startsWith(buzzReplace))
If you think about the types involved here, clearly a string cannot start with an array of strings. A string can possibly start with another string.
So you need to iterate over the contents of your buzzReplace list:
for(String name : names)
{
for (String vowel : buzzReplace)
{
if (name.startsWith(vowel))
{
//do something
}
}
}
Your use of replaceAll is also incorrect and does not match the method signature. I'll leave it up to you to fix that element of your code. (a hint: you do not need to modify the contents of the list)
With Java 8 you could do something like this:
public List<String> buzz(List<String> names) {
List<Character> buzzChars = Arrays.asList('a', 'e', 'i', 'o', 'u');
return names.stream()
.map(name -> buzzChars.contains(name.toLowerCase().charAt(0)) ? "Buzz" : name)
.collect(Collectors.toList());
}
Instead of
if(value.startsWith(buzzReplace))
try
String[] buzzReplace ={"a","e","i","o","u"};
if (Arrays.asList(buzzRepalce).contains(value.subString(0,1))
This answer idea is like Jamesp's answer but as your code has some bugs and maybe you face them in next step, I send whole method.
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Harry");
names.add("Kathy");
names.add("aathy");
ArrayList<String> replaceArray = new ArrayList<>();
String[] buzzReplace ={"a","e","i","o","u"};
for(String value:names)
{
if(Arrays.asList(buzzReplace).contains(value.substring(0,1)))
{
replaceArray.add("Buzz");
}
else replaceArray.add(value);
}
System.out.println(Arrays.toString(replaceArray.toArray()));
}
Write some method that does the task. let say. getReplacedList(List<String> names)
Now get the replaced array from that method.
private static List<String> getReplacedList(List<String> names) {
ArrayList<String> replaceArray = new ArrayList<>();
String buzzReplace = "aeiou";
names.stream().forEach(name ->{
//user to lower case if you want to ignore case.
if (buzzReplace.contains(name.toLowerCase().charAt(0)+"")) {
//do some thing like
replaceArray.add("Buzz");
} else {
replaceArray.add(name);
}
});
return replaceArray;
}
Now pass your original list to this method to get the replaced list.
Your solution look like.
public static void main(String... args) {
ArrayList<String> names = new ArrayList<>();
names.add("Harry");
names.add("Kathy");
List<String> replaceArray = new ArrayList<>();
replaceArray = getReplacedList(names);
//do some thing with replace array.
System.out.println(replaceArray.toString());
}
private static List<String> getReplacedList(List<String> names) {
ArrayList<String> replaceArray = new ArrayList<>();
String buzzReplace = "aeiou";
names.stream().forEach(name ->{
//user to lower case if you want to ignore case.
if (buzzReplace.contains(name.toLowerCase().charAt(0)+"")) {
//do some thing like
replaceArray.add("Buzz");
} else {
replaceArray.add(name);
}
});
return replaceArray;
}

Removing special characters from string

I want to parse this string into a list and return {1.193493, 54.6333, 2.093077, 31.6235, 6.175355, 21.6479}. How do I get rid of the square brackets???? I used a for loop and replace but it doesn't work.
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]"
String[] parsed = st.split(",");
for (String next : parsed) {
next.replace("//[", "").replace("//]", "");
}
replace() works with plain Strings, not regex. Therefore you can simply use:
next.replace("[", "").replace("]", "");
Also notice that you need to assign it to some string variable; assigning it to need won't work (won't modify elements in parsed array).
You should actually remove the braces first and split later, like this:
String[] parsed = st.replace("[", "").replace("]", "").split(",");
You can do it all at one time with this regex:
(?:\D*(\d*\.\d*))+
You can do this with one line:
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
Full code:
package com.stackoverflow;
import java.util.Arrays;
import java.util.List;
public class Demo
{
public static void main(String[] args)
{
String t = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
for(String s : list)
{
System.out.println(s);
}
}
}
Converts string to list of strings and prints it. If you need to convert strings to doubles, use Double.parseDouble(s) in loop.
You could achieve your goal in two steps.
1) Remove all special characters except comma (,)
2) Then split by comma (,)
public static void main(String[] args) {
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
String[] parsed = st.replaceAll("[^\\d.,]+", "").split(",");
}
Output:

How to skip a particular string during string Joining in Java?

The source code I have uploaded it will join some strings value in a one line. I want a way that I can able to skip a particular string in time of string joining. Here i have stored the strings "This","is","a","test." in a string array. I want that in time of joining a particular string will be skipped. Like I want to skip "a". How can I able to do in Java? I want a generalized way that I will able to apply for any strings.
import java.util.StringJoiner;
public class Test_Joiner_for_seatPlan
{
public static void main(String[] args)
{
StringJoiner joinString = new StringJoiner( " ");
String[] testStringArray = {"This","is","a","test."};
String joinedString = null;
for(String s : testStringArray)
{
joinString.add(s);
}
joinedString = joinString.toString();
System.out.println("After Joining the String:\n"+joinedString);
}
}
Try with not equal condition with string. but its not feasible as its check everytime a value.
for(String s : testStringArray)
{
if(!s.equals("a")){
joinString.add(s);
}
}
If you have a list of values like a,b,c than you can do like this:
Set<String> exclude = new HashSet<String>(Arrays.asList("a","b","c"));
for(String s : testStringArray)
{
if(!exclude.contains(s)){
joinString.add(s);
}
}
Use Split method of string. It returns array. combine each of them to get the string.
for (String retval: Str.split("a")){
System.out.println(retval);
}
You can do it like this:
Code:
for(String s : testStringArray){
if(!s.equals("a")){ // replace 'a' with the required character or word you want to ignore
joinString.add(s);
}
}
One possible solution is to provide a Map or a List in which you store the String values that should get excluded in your join. Here is an example using a Map.
public static void main(String[] args) {
String[] testStringArray = {"This","is","a","test."};
Map<String, String> excludedStrings = createExcludingMap("a");
System.out.println("After Joining the String:\n" + join(testStringArray, excludedStrings));
}
private static String join(String[] inputData, Map<String, String> excludedStrings){
StringJoiner joinString = new StringJoiner( " ");
String joinedString = null;
for(String s : inputData)
{
if(excludedStrings.get(s) == null) // IF this return null, the String is not part of the Strings to be excluded, hence join the string
joinString.add(s);
}
joinedString = joinString.toString();
return joinString.toString();
}
private static Map<String, String> createExcludingMap(String... values) {
Map<String, String> output = new HashMap<>();
for(String s : values) { // Add each value to the map, with s as key
output.put(s, s);
}
return output;
}
output :/
After Joining the String:
This is test.
The StringJoiner is a utility class that was written specifically to be used with the new Java8 Stream functionality. The documentation of StringJoiner also refers to the Collectors.joining method. It creates the StringJoiner, and wraps it in an object suitable to pass to Stream.collect, actually a Collector.
As part of the Stream API we now also have direct support for filters, it is just a matter of employing the fluent API (fluent because we keep adding .something(...)) to add the .filter method.
You can use it as you did in your answer, but I would suggest doing it as follows:
import static java.util.stream.Collectors.joining;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class App {
public static String joinString(String [] sa,Predicate<String> filter) {
return Stream.of(sa).filter(filter).collect(joining(" "));
}
public static void main(String[] args) {
String[] testStringArray = new String [] {"This","is","a","test."};
System.out.println(joinString(testStringArray,(s)->!s.equals("a")));
}
}
I have deliberately broken it up by defining an extra method, so you can see the type of the filter passed along, exposing the Predicate. This would also make your function a little more generic making it work as you stated: 'I want a generalized way that I will able to apply for any strings'.
However if the Stream api is flexible enough that I do not see any need to abstract your own API for it. I suggest using it as-is:
import static java.util.stream.Collectors.joining;
import java.util.stream.Stream;
public class App {
public static void main(String[] args) {
System.out.println(
Stream
.of(new String [] {"This","is","a","test."})
.filter((s)->!s.equals("a"))
.collect(joining(" "))
);
}
}
I could have written most of it on a single line, but I like to break it up for readability.

when i try to add to treeset it returns blank

i have an assignment for school and this is what i have so far with notes of what i'm trying to do
import java.io.*;
import java.util.Scanner;
public class UniquesDupesTester
{
public static void main( String args[] ) throws IOException
{
// make a Scanner and associate it with "UniquesDupes.dat"
// as long as there are Strings in the file
// read in a String,
// create a UniquesDupes object with it
// print the object
Scanner in = new Scanner(new File("UniquesDupes.dat"));
while (in.hasNextLine())
{
String n = in.nextLine();
UniquesDupes a = new UniquesDupes(n);
a.getUniques();
a.getDupes();
System.out.println (a);
}
}
}
seperate file
import java.util.Set;
import java.util.TreeSet;
import java.util.Arrays;
import java.util.ArrayList;
public class UniquesDupes
{
private ArrayList<String> list;
/**
* constructs a UniquesDupes object such that list contains the space delimited strings
* parsed from input
* #param input a String containing the list of words separated by spaces
*/
public UniquesDupes(String input)
{
list = new ArrayList<String>();
String[] words = "abc cde fgh ijk".split(" ");
ArrayList<String> list = new ArrayList<String>(Arrays.asList(words));
}
/**
* returns a set of Strings containing each unique entry in the list
*/
public Set<String> getUniques()
{
Set<String> uniques = new TreeSet<String>();
for(String a:list)
{
uniques.add(a);
}
return uniques;
}
/**
* returns a set of Strings containing each entry in the list that occurs more than once
*/
public Set<String> getDupes()
{
Set<String> uniques = new TreeSet<String>();
Set<String> dupes = new TreeSet<String>();
for(String a:list)
{
uniques.add(a);
{
if(uniques.add(a) == false)
{
dupes.add(a);
}
}
}
return dupes;
}
/**
* returns the original list, the list of duplicates and the list of uniques
* #return the String version of the object
*/
public String toString()
{
return "Orig list :: " + list
+ "\nDuplicates :: " + getDupes()
+ "\nUniques :: " + getUniques() + "\n\n";
}
}
here is the dat file if you need it
a b c d e f g h a b c d e f g h i j k
one two three one two three six seven one two
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 6
it compiles and runs but all the files return blank i have no idea what i did wrong help or hints would be appreicated
The logic is almost correct.
The UniquesDupes class is almost OK, but the constructor is not OK. It should just be
public UniquesDupes() // no args, default constructor
{
list = new ArrayList<String>(); //just initialize the list
}
At the same time, said class would need an addString method:
public void addString(String input) {
String[] words = input.trim().split(" "); //split the input string into words by spaces, after trimming whitespace
this.list.addAll(Arrays.asList(words)); //adding them to the list.
}
The while loop should be changed a bit. You want only 1 instance of the UniquesDupes class, and then add each line using the addString method created before.
UniquesDupes a = new UniquesDupes(); //create it here
while (in.hasNextLine())
{
String n = in.nextLine();
a.addString(n); //adding the string
}
Then the results need to be handled differently
Collection<String> uniques = a.getUniques();
Collection<String> dupes = a.getDupes();
System.out.println (uniques.toString());
System.out.println (dupes.toString());
That said, the logic was almost right...
An ugly thing you did is however this part:
list = new ArrayList<String>(); //using instance variable
String[] words = "abc cde fgh ijk".split(" ");
ArrayList<String> list = new ArrayList<String>(Arrays.asList(words));
// ^^ declaring local variable the same name as the instance variable
This is bad. You shouldn't do it. No-no. Don't do it again! Picking up this habit makes code exceptionally hard to read, and crazy insane to maintain...

Java:HashMap<String,String> storing same value as key and value.?

I am getting this strange output in HashMap.
I have two ArrayList<String> one containing the key and another containing value.
My HashMap<String,String> will store only string as key and value pair. But key itself is getting stored in value. I have checked my value arraylist, it's printing the value. But during putting it's setting it as key itself.
Code snippet is:
public HashMap<String,String> getLstBarring()
{
ArrayList<String> temparrLst=setPreParameters(fetchPreDetails, 1);
System.out.println("KEY" + temparrLst);
ArrayList<String> tempArrLstId=setPreParameters(fetchPreDetails, 14);
System.out.println("VALUE" +tempArrLstId);
int length=tempArrLstId.size();
for(int index=0;index<length;index++)
{
System.out.println("VALUE IN KEY" + temparrLst.get(index));
System.out.println("VALUE IN VALUE" + tempArrLstId.get(index));
this.lstBarring.put(temparrLst.get(index), tempArrLstId.get(index));
}
System.out.println("INSIDE ODB....>>>>>>>>>>>>>>" + lstBarring);
return this.lstBarring;
}
Problem is:
1st SOP is KEY-printing all the key correctly.
2nd SOP is VALUE-printing all the value correctly.
3rd SOP is VALUE IN KEY----printing all the values.
4th SOP is VALUE IN VALUE--printing all the values.
Hence after ever iteration I am getting value,value in HashMap whereas it should be key,value.
Here's look at my Method:-
public ArrayList<String> setPreParameters(HashMap<Integer,String> fetchPreDetails,int index)
{
switch(index)
{
case 1:
{
arrLstData.clear();
splittedString=fetchPreDetails.get(1).split(",");
Collections.addAll(arrLstData, splittedString);
break;
}
return arrLstData;
Please guide me as to where am I going wrong.
My guess is that either fetchPreDetails is a collection being mutated by setPreParameters() or else setPreParameters() is mutating some other shared state so that the collection referenced by your temparrLst is being changed on the second call to setPreParameters(). I.e.
List<String> strings = new ArrayList();
strings.add("a");
strings.add("b");
List<String> otherStrings = strings;
otherStrings.add("c");
I expect your code assumes that strings would contain "a" and "b" and that otherStrings would contain "a", "b", and "c". This isn't how object references work in Java. The line List<String> otherStrings = strings; makes both strings and otherStrings point to the same collection, and thus changes made using either name affect the same thing.
Edit: Your newly-posted code seems to prove my hypothesis. You have a variable called arrLstData that you clear, populate, and return on each call to setPreParameters(). You're returning the same collection every time you call this method. Therefore you just have multiple handles to the same collection instead of multiple collections. You need to create a new collection and return it each time you call setPreParameters().
Edit again: Maybe this will make it clearer. Here's what you're doing:
public static void main(String[] args) {
Foo f = new Foo();
List<String> list1 = f.getList("a", "b");
System.out.println(list1);
List<String> list2 = f.getList("c", "d");
System.out.println(list2);
System.out.println(list1);
}
static class Foo {
private List<String> myList = new ArrayList<String>();
public List<String> getList(String... strings) {
myList.clear();
myList.addAll(Arrays.asList(strings));
return myList;
}
}
Note that this exhibits exactly the behavior that you're describing, and the correct way to solve it is something like this:
public static void main(String[] args) {
Foo f = new Foo();
List<String> list1 = f.getList("a", "b");
System.out.println(list1);
List<String> list2 = f.getList("c", "d");
System.out.println(list2);
System.out.println(list1);
}
static class Foo {
public List<String> getList(String... strings) {
List<String> result = new ArrayList<String>();
result.addAll(Arrays.asList(strings));
return result;
}
}
You are reusing the same List over and over at your setPreParameters Method.
The List in arrLstData is returned and stored in temparrLst, now you are clearing the the Lists content, putting new stuff in it and storing it to tempArrLstId.
Now the three variables all contain the very same list (they are not equals, its the same!).
There is only one List object at the whole example!
Its like you got a box and label it "A" on one side put stuff in it, label it "B" on another side and wondering why the box "B" is empty when you turn box "A" upside-down.
Did you maybe mean something like this?
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GlobalsMess {
private Map<String, String> lstBarring = new HashMap<String, String>();
private Map<Integer, String> fetchPreDetails = new HashMap<Integer, String>();
public GlobalsMess() {
fetchPreDetails.put(1, "john,vikam,david");
fetchPreDetails.put(14, "1,2,3");
}
public Map<String, String> getLstBarring() {
List<String> tempKeys = setPreParameters(fetchPreDetails.get(1));
System.out.println("KEY" + tempKeys);
List<String> tempIds = setPreParameters(fetchPreDetails.get(14));
System.out.println("VALUE" + tempIds);
for (int index = 0; index < tempIds.size(); index++) {
System.out.println("VALUE IN KEY" + tempKeys.get(index));
System.out.println("VALUE IN VALUE" + tempIds.get(index));
this.lstBarring.put(tempKeys.get(index), tempIds.get(index));
}
System.out.println("INSIDE ODB....>>>>>>>>>>>>>>" + lstBarring);
return this.lstBarring;
}
public List<String> setPreParameters(String fetchPreDetailsValue) {
List<String> arrLstData = new ArrayList<String>();
Collections.addAll(arrLstData, fetchPreDetailsValue.split(","));
return arrLstData;
}
public static void main(String[] args) {
new GlobalsMess().getLstBarring();
}
}
Output:
KEY[john, vikam, david]
VALUE[1, 2, 3]
VALUE IN KEYjohn
VALUE IN VALUE1
VALUE IN KEYvikam
VALUE IN VALUE2
VALUE IN KEYdavid
VALUE IN VALUE3
INSIDE ODB....>>>>>>>>>>>>>>{david=3, vikam=2, john=1}

Categories

Resources