How to replace a string starting with a letter in Java - 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;
}

Related

How to group arrays in arraylist by matching a value inside the inner arrays?

I have an ArrayList which contains several String[]. I want to loop through the ArrayList and group the inner String[] that contain a matching value. In this case, I'm looking specifically at the second value in the String[] (ex. "CompanyA").
I'm having difficulty understanding what the best logical pattern for this is and how it might be implemented. Any help is greatly appreciated.
List<String[]> attArrayList = new ArrayList<String[]>();
String[] entry1 = { "EventOne", "CompanyA", "Matthew" };
String[] entry2= { "EventOne", "CompanyA", "Mary" };
String[] entry3 = { "EventOne", "CompanyB", "Bates" };
String[] entry4 = { "EventOne", "CompanyC", "Carson" };
attArrayList.add(entry1);
attArrayList.add(entry2);
attArrayList.add(entry3);
attArrayList.add(entry4);
for (int i = 0; i < attArrayList.size(); i++) {
// ...
}
My desired result is something like this:
[[EventOne, CompanyA, Matthew], [EventOne, CompanyA, Mary]], [EventOne, CompanyB, Bates], [EventOne, CompanyC, Carson]
Map<String, ArrayList<String[]>> map = new TreeMap<>();
for (String[] strs : attArrayList) {
if (!map.containsKey(strs[1])) {
ArrayList<String[]> list = new ArrayList<>();
list.add(strs);
map.put(strs[1], list);
} else {
map.get(strs[1]).add(strs);
map.put(strs[1], map.get(strs[1]));
}
}
for (String[] strs : map.get("CompanyA")) {
System.out.println(Arrays.toString(strs));
}
You can try this.I think it`s easier to understand than using stream(though stream has less code).
You could use groupingBy to group the items based on the second column:
Map<String, List<String[]>> groups = attArrayList.stream()
.collect(groupingBy(arr -> arr[2]));

Replace values in a list

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.

String inside ArrayList<String[]>

How to check whether a specific String is present inside ArrayList<String[]>?
Whether I need to iterate each item and check for the string or any specific method for this purpose is present (like ArrayList.contains() )?
Tried ArrayList.contains() but not working in my case.
It is not an ArrayList <String> it is ArrayList<String[]> so this question is not a duplicate one and am asking this for a curiosity whether any special method is present or not
This is a example program to get what you asked for... hope it helps
public static void main(String[] args) {
ArrayList<String []> a = new ArrayList<>();
String b[] = {"not here","not here2"};
String c[] = {"not here3","i'm here"};
a.add(b);
a.add(c);
for (String[] array : a) {// This loop is used to iterate through the arraylist
for (String element : array) {//This loop is used to iterate through the array inside the arraylist
if(element.equalsIgnoreCase("i'm here")){
System.out.println("found");
return;
}
}
}
System.out.println("match not found");
}
You can do it easily with streams:
String contains;
List<String[]> strings;
boolean isPresent = strings.stream().flatMap(Arrays::stream).anyMatch(contains::equals);
Well, you need to traverse whole list and then traverse each array inside it to find the item.
String valToBeSearched="abc";
for(String [] arr: list)
{
for(String str: arr)
{
if(str.equals(valToBeSearched)){ // do your stuff}
}
}
Using Java 8 streams, you can do this:
public boolean containsString(List<String[]> list, String s) {
// Gives you a Stream<String[]>.
return list.stream()
// Maps each String[] to Stream<String> (giving you a
// Stream<Stream<String>>), and then flattens it to Stream<String>.
.flatMap(Arrays::stream)
// Checks if any element is equal to the input.
.anyMatch(Predicate.isEqual(s));
}
You could iterate over the ArrayList with two for-each loops:
import java.util.Arrays;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String[]> arrayList = new ArrayList<String[]>();
String[] fruit = {"Apple", "Banana"};
String[] pets = {"Cat", "Dog"};
arrayList.add(fruit);
arrayList.add(pets);
System.out.println(Arrays.deepToString(arrayList.toArray())); //[[Apple, Banana], [Cat, Dog]]
System.out.println(arrayListContains(arrayList, "Apple")); //true
System.out.println(arrayListContains(arrayList, "Orange")); //false
}
public static boolean arrayListContains(ArrayList<String[]> arrayList, String str) {
for (String[] array : arrayList) {
for (String s : array) {
if(str.equals(s)) {
return true;
}
}
}
return false;
}
}
Try it here!
Try to take a look at Guava Iterables.concat().
It can be used to flatten Iterable of Iterables, i'm not sure it will work on an Iterable of Array but it's just a little transformation...
If you can flatten your list, you could then use the "contains" method on the result.

How to split a string into a map with a list of values?

I am a bit stuck with my application, and I am not quite sure what to search for. So I am hoping someone here may help me out.
I have a list of Strings, that looks like this:
Cake;carrot
Cake;apple
Cake;spicy
Pizza;pepperoni
Pizza;mozzarella
... and so on. I want to put this data into a Map<String, List<String>>, where Cake and Pizza will make up the keys in my Map. Having [carrot, apple, spicy] as Cake's values, and [pepperoni, mozzarella] as Pizza's values.
How may I achieve this? Thanks in advance for any help.
Just iterate over your list using String.split()
ArrayList<String> myList;
HashMap<String, List<String>> myMap = new HashMap<>();
for(String s : myList)
{
String[] split = s.split(";");
List<String> bucket = myMap.get(split[0]);
if(bucket == null)
{
bucket = new ArrayList<String>();
myMap.put(split[0], bucket);
}
bucket.add(split[1]);
}
You can try this, use a hashmap, store consecutive strings with (space) as the delimiter, finally split the string when you want it as a list
//Assuming your list to be the variable 'list'
HashMap<String,String> hm = new HashMap<>();
for(val : list){
String st[] = val.split(";");
if(hm.get(st[0])==null){
hm.put(st[0],st[1]);
}
else{
hm.put(st[0],hm.get(st[0])+" "+st[1]);
}
}
when You want the string array of say pizza back then
String pizz[] = (hm.get("pizza")).split(" ");
pizz[] will have your array, cheers!
public static void main(String[] args) {
List<String> data = new ArrayList<String>();
Map<String, List<String>> finalData = new HashMap<String,List<String>>();
data.add("Cake;carrot");
data.add("Cake;apple");
data.add("Cake;spicy");
data.add("Pizza;pepperoni");
data.add("Pizza;mozzarella");
for (String dataString : data) {
List<String> temp = null;
if (finalData.get(dataString.split(";")[0]) == null) {
temp = new ArrayList<String>();
temp.add(dataString.split(";")[1]);
finalData.put(dataString.split(";")[0], temp);
} else {
temp = finalData.get(dataString.split(";")[0]);
temp.add(dataString.split(";")[1]);
finalData.put(dataString.split(";")[0], temp);
}
}
System.out.println(new Gson().toJson(finalData));
}
Complete working solution.

Java ArrayList<String> .contains() in hadoop

I am trying to remove the duplicated strings in an ArrayList called outputList in Hadoop.
Here is my code:
List<String> newList = new ArrayList<String>();
for( String item : outputList){
if(!newList.contains(item))
newList.add(item);
else newList.add("wrong");
}
The problems is that the strings in newList are all "wrong".
Some facts:
1. The above code works well at local machine.
I can write out the strings in outputList in hadoop. Most strings in outputList are different (duplicates exist).
I tried some other method to remove duplicated items. Like using HashSet. But when I use outputList to initialize a HashSet, the obtained HashSet is empty.
The java version in Hadoop is javac 1.6.0_18
Thanks.
The following is my reducer code:
public static class EditReducer
extends Reducer<Text,Text,Text,Text> {
private Text editor2 = new Text();
public void reduce(Text key, Iterable<Text> values,
Context context
) throws IOException, InterruptedException {
//write the content of iterable to an array list.
List<String> editorList =new ArrayList<String>();
for (Text t:values) {
editorList.add(t.toString());
}
//if a user appears more than once in the list, add to outputList
int occ;
List<String> outputList =new ArrayList<String>();
for (int i=0;i<editorList.size();i++) {
occ= Collections.frequency(editorList, editorList.get(i));
if(occ>1) {
outputList.add(editorList.get(i));
}
}
//make outputList distinct
List<String> newList = new ArrayList<String>();
for( String item : outputList){
if(!newList.contains(item))
newList.add(item);
else newList.add("wrong");
}
for (String val : newList) {
editor2.set(val);
context.write(editor2,editor2);
}
}
}
You can create a nested for loop inside your original for loop and compare the strings that way:
List<String> newList = new ArrayList<String>();
for(String item : outputList) {
boolean contains = false;
for(String str: newList) {
if(str.equals(item)) {
contains = true;
break;
}
}
if(!contains) {
newList.add(item);
}
else {
newList.add("wrong");
}
}

Categories

Resources