How to pass dynamic string values to a method? - java

I am trying to create a method that should dynamically accept the string values and store it in an array list.Am trying to achieve method overloading here. Please see the below example and help me resolve in this:
public static void main(String[] args){
verifyFilesInFolder("folder1", "file1", "file2", "file3");
verifyFilesInFolder("folder2", "file1", "file2");
}
verifyFilesInFolder(String folder, ArrayList ???)
{
List<String> list = new ArrayList<String>();
int size=list.size();
for(int i=0; i<size;i++){
list.add(i); // is this correct??
}
}
After storing it in the array list, i want to compare this expected list with Actual list captured from the application by sorting.
Hope you got the point am looking for. If not ArrayList, please suggest me a way to achieve this by having only one method but the number of files may change while calling that method.

You have 2 options:
Overloading
Define mulitple methods with the same names but different numbers of arguments:
public void func(String s1) { ... }
public void func(String s1, String s2) { ... }
public void func(String s1, String s2, String s3) { ... }
Varargs
Define a single method that takes any number of args:
public void func(String ...strings) {
// strings is of type String[]
String s1 = strings[0];
String s2 = strings[1]; // note, be careful with ArrayIndexOutOfBoundsException
// generally use a for-each loop
}
This can be called as:
func("1");
func("1", "2");
func("1", "2", "3");
func(new String[] {"1", "2", "3"});
EDIT:
If you want to add these values to a List, you can do this:
verifyFilesInFolder(String folder, String ...strings) {
List<String> list = Arrays.asList(strings);
for (String s : list) System.out.println(s);
}
Some inputs/outputs:
verifyFilesInFolder("folder", "item1"); -> prints "item1"
verifyFilesInFolder("folder", "item1", "item2"); -> prints "item1" and "item2"
verifyFilesInFolder("folder"); -> prints nothing
verifyFilesInFolder(); -> won't compile

Related

How to add characters in the middle of a word in an arraylist in java?

I'm practicing ArrayList's. I'm trying to make it so that every time is is in the ArrayList, it is then followed with not. For instance [is sky, is, this is blue, is is, is not] after running through the method comes out as [is not sky, is not, this is not blue, is not is not, is not not]. However, with my code right now it does not change. I am new to Java, so I would really appreciate any pointers!
class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("is sky");
list.add("is");
list.add("this is blue");
list.add("is is");
list.add("is not");
System.out.println(replace(list));
}
public static ArrayList<String> replace(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
if (list.subList(i, i + 1).equals("is")) {
list.add(i + 1, " not");
}
}
return list;
}
}
First solve the simplest case. Forget the list for a moment and do the substitution with just one String.
String replaceOne(String original) {
return original.replace("is", "is not");
}
Test this method.
String replaced = replaceOne("sky is");
The test passes if this replaced variable is equal to sky is not.
Once you've guaranteed that, move on to the general case, with a list.
void replaceMany(ArrayList<String> original) {
for (int i = 0; i < original.size(); i++) {
original.set(i, replaceOne(original.get(i)));
}
}
Note that if you're running this inside a static method, the above methods need to be static (i.e. static void, static String).
With Java 8 you could also solve this problem differently. Instead of using the set method on the array list, you could use lambdas and a collector to get a modified list (preserve the original and get another list with the modified strings). Something like:
List<String> replaced = original.stream()
.map(s -> replaceOne(s))
.collect(Collectors.toList());
With Java 9, you can simplify your code as follows:
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> list = List.of(
"is sky", "is", "this is blue", "is is", "is not");
System.out.println(replace(list));
}
public static List<String> replace(List<String> list) {
return list.stream()
.map(str -> str.replace("is", "is not"))
.collect(Collectors.toList());
}
}
Output:
[is not sky, is not, this not is not blue, is not is not, is not not]
Because your if statement is always false. Method subList returns list that you compare with string in line:
list.subList(i, i+1).equals("is")

Java - Comparing a single String value with all the String values in an ArrayList

I have an ArrayList with a set of (same) string values which I need to compare with a single String value and return true or false. Is there any way to do
that in Java?
For example, say I have a <String>ArrayList with 5 values = foo, foo, foo, foo, foo (My requirement is such that all the values in the arraylist will be the SAME) and I have a String str = "foo". I need to verify that whether ALL the values in the arraylist is the SAME as the string value i.e., all the values present in the arraylist SHOULD be "foo".
I tried to google this info and all I can see is suggestions to use contains() method, in different ways, which will return true even if anyone value in the arraylist contains the specified value.
I even figured a workaround for this - Creating another arraylist with expected values and compare the two lists using equals() method and it seems
to be working. I was just wondering whether there is any simple way to achieve this.
That's simple with Java 8:
String str = "foo";
List<String> strings = Arrays.asList("foo", "foo", "foo", "foo", "foo");
boolean allMatch = strings.stream().allMatch(s -> s.equals(str));
For Java 7 replace the last line with:
boolean allMatch = true;
for (String string : strings) {
if (!string.equals(str)) {
allMatch = false;
break;
}
}
If you want to know if the array contains the string use ArrayList::contains()
String s = "HI";
ArrayList<String> strings = // here you have your string
if (string.contains(s)) {
// do your stuff
}
If you want to check if all values are same, iterate and count. If you have JAVA8 check steffen sollution.
boolean areSame = true;
for (String str : strings) {
if (!str.equals(s)) areSame = false;
}
if (areSame) {
// all elements are same
}
1) You can the pass the arraylist into a set.
2) Now you can get the size of set, if it is equal to 1 that means all elements are same.
3) Now you can use the contains on set to check if your value is present in it or not.
public static void main(String[] args){
String toBeCompared="foo";
List<String> list=new ArrayList<String>();
list.add("foo");
list.add("foo");
list.add("foo");
list.add("foo");
list.add("foo");
Set<String> set=new HashSet<String>(list);
if(1==set.size()){
System.out.println(set.contains(toBeCompared));
}
else{
System.out.println("List has different values");
}
}
You can use this method to do that
private boolean allAreSame(ArrayList<String> stringList, String compareTo){
for(String s:stringList){
if(!s.equals(compareTo))
return false;
}
return true;
}
I would do it like this:
ArrayList<String> foos = new ArrayList<>();
String str = "foo";
for (String string : foos) {
if(string.equals(str)){
System.out.println("True");
}
}

Remove duplicate element from the set in java [duplicate]

This question already has answers here:
Storing arrays in Set and avoiding duplicates
(6 answers)
Closed 9 years ago.
I have set of string array and i want to remove duplicate elements from this...
String[] arr1 = {"a1","b1"};
String[] arr2 = {"a2","b2"};
Set<String[]> mySet = new HashSet<String[]>();
mySet.add(arr1);
mySet.add(arr2);
mySet.add(new String[] {"a1","b1"});
System.out.print(mySet.size());
Currently mySet looks like this:
[{"a1","b1"},{"a2","b2"},{"a1","b1"}]
But I want like this:
[{"a1","b1"},{"a2","b2"}]
I know some ways...
Every time I need to run inner loop and check whether its duplicate or not.
Can I override the set's behavior? (hashcode or equals)? ( i do not know how....)
Do I need to change data structure for this? (linkedhashset or list or any other suitable data structure for this?)
Arrays inherit from Object and don't override the hashCode and equals methods. A HashSet uses a Map implementation, which in turn, uses hashCode and equals to avoid duplicate elements.
You can use a TreeSet with a custom Comparator that compares the String arrays for equality.
Set<String[]> mySet = new TreeSet<>(new Comparator<String[]>() {
#Override
public int compare(String[] o1, String[] o2) {
return Arrays.equals(o1, o2)? 0 : Arrays.hashCode(o1) - Arrays.hashCode(o2);
}
});
Note that this will only neglect duplicate arrays with the same corresponding elements. If the order of elements is different, it won't be considered as a duplicate.
If you want to be able to discard unordered duplicates, for e.g., {a1, b1} and {b1, a1}, use this:
#Override
public int compare(String[] o1, String[] o2) {
int comparedHash = o1.hashCode() - o2.hashCode();
if(o1.length != o2.length) return comparedHash;
List<String> list = Arrays.asList(o1);
for(String s : o2) {
if(!list.contains(s)) return comparedHash;
}
return 0;
}
The array hashcode is independent of the contents of the array (it inherits the Object hashcode, which uses the array's reference).
However, List would do what you want. It uses a hashcode based on the elements in the List . From Java Docs:
int hashCode = 1;
for (E e : list)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
Example:
List<String> list1 = Arrays.asList("a1","b1");
List<String> list2 = Arrays.asList("a2","b2");
Set<List<String>> mySet = new HashSet<List<String>>();
mySet.add(list1);
mySet.add(list2);
mySet.add(Arrays.asList("a1","b1")); // duplicate won't be added
System.out.print(mySet.size()); // size = 2
Arrays uses identity-based Object.hashCode() implementation and there is no easy way to check if they are equal. If it all you still want to go ahead with your problem I would suggest you to use TreeSet with Comparator
Though not fail proof approach, but you should be able to build fine tuned solution out of my example,
public static void main(String[] args) {
String[] arr1 = {"a1","b1"};
String[] arr2 = {"a2","b2"};
Set<String[]> mySet = new TreeSet<String[]>(new ArrayComparator());
mySet.add(arr1);
mySet.add(arr2);
mySet.add(new String[] {"a1","b1"});
System.out.println(mySet.size());
for(String[] aa: mySet){
System.out.println(aa[0]+" , "+aa[1]);
}
}
}
class ArrayComparator implements Comparator {
#Override
public int compare(Object o1, Object o2) {
String[] ar1 =(String[]) o1;
String[] ar2 =(String[]) o2;
if(ar1.length!=ar2.length){
return -1;
}
for(int count=0;count<ar1.length;count++){
if(!ar1[count].equals(ar2[count])){
return -1;
}
}
return 0;
}
Why not use a List implementation? The list.equals will compare elements in each list and determine equality.
List<String> arr1 = new ArrayList<String>();
arr1.add("a1");
arr1.add("b1");
List<String> arr2 = new ArrayList<String>();
arr2.add("a2");
arr2.add("b2");
Set<List<String>> mySet = new HashSet<List<String>>();
mySet.add(arr1);
mySet.add(arr2);
List<String> arr3 = new ArrayList<String>();
arr3.add("a1");
arr3.add("b1");
mySet.add(arr3);
System.out.print(mySet.size());
You suggest overriding equals and hashcode methods. HashSet is backed by a hashmap that uses the hashcode function as its key. So actually you need to override hashcode to represent your equals criteria.
One problem with this. I believe String and therefore String [] are declared as final, so you can't extend them :(
instead of taking array of string you can create a class Like this..
public class String1 implements Comparable<String1>{
String str1;
String str2;
public String1(String a, String b) {
str1 = a;
str2 = b;
}
public String getStr1() {
return str1;
}
}
public String getStr2() {
return str2;
}
#Override
public String toString() {
return "String1 [str1=" + str1 + ", str2=" + str2
+ "]";
}
#Override
public int compareTo(String1 o) {
if(str1.contentEquals(o.getStr1()) && str2.contentEquals(o.getStr2())) return 0 ;
return 1;
}
}
And after that insteed of string you can take this one class object.
replace HashSet with TreeSet. Like this .
String1 arr1 =new String1("a1","b1");
String1 arr2 =new String1("a2","b2");
Set<String1> mySet = new TreeSet<String1>();
mySet.add(arr1);
mySet.add(arr2);
mySet.add(new String1("a1","b1"));
System.out.print(mySet.size());
System.out.println(mySet.toString());
So this will sort as well this will check for duplicate also.
try to this code.............
import java.util.HashSet;
import java.util.Set;
public class setDemo {
static Set<String[]> mySet = new HashSet<String[]>();
static Set tempSet = new HashSet();
public static void main(String[] args) {
String[] arr1 = {"a1","b1"};
String[] arr2 = {"a2","b2"};
addObject(arr1);
addObject(arr2);
addObject(new String[] {"a1","b1"});
System.out.print(mySet.size());
// System.out.println(tempSet);
}
public static void addObject(String[] o){
StringBuffer sb = new StringBuffer();
for(Object obj:o){
sb.append(obj.toString());
}
if(!tempSet.contains(sb.toString())){
tempSet.add(sb.toString());
mySet.add(o);
}
}
}
Try something like this...
public static void main(String... args) {
String[] arr1 = {"a1","b1"};
String[] arr2 = {"a2","b2"};
Set<String[]> mySet = new HashSet<String[]>();
mySet.add(arr1);
mySet.add(arr2);
String str[] =new String[] {"a1","b1"};
long t1 = System.nanoTime();
boolean b =checkContains(str,mySet);
long t2=System.nanoTime();
long t = t2-t1;
System.out.println("time taken : " + t );
System.out.println(b);
if(!b)
{
mySet.add(str);
}
}
public static boolean checkContains(String[] str, Set mySet)
{
Iterator it = mySet.iterator();
while(it.hasNext())
{
String[] arr = (String[])it.next();
if(arr[0].equals(str[0]) && arr[1].equals(str[1]) )
{
return true;
}
}
return false;
}
OP :
time taken : 184306
true
Here instead of keeping Set you can use Set<SomeClass> and the override the hash and equals method for the class SomeClass so it will solve your problem.

Looping in ArrayLists with a Method

With much assistance I have developed a method that makes anagrams and then adds them into an ArrayList.
public void f(String s, String anagram, ArrayList<String> array)
{
if(s.length() == 0)
{
array.add(anagram);
return;
}
for(int i = 0 ; i < s.length() ; i++)
{
char l = s.charAt(i);
anagram = anagram + l;
s = s.substring(0, i) + s.substring(i+l, s.length());
f(s,anagram,array);
}
}
The problem is when I attempt to use this function to make ArrayLists in a loop that adds Strings from one ArrayList to another, I get an error saying I can't use a void, and the method f() is void.
List<String> Lists = new ArrayList<String>(); //makes new array list
for(String List : words)
{ //takes values from old array list
List.trim();
Lists.add(f(List,"",new ArrayList<String>())); //this is where it doesn't work
}
Let me clarify once more:
I want to use this function to insert ArrayLists of anagrams into each position in another ArrayList. The anagram Lists are derived from Strings that are being read from one list to another. I tried changing the method to static but that doesn't work, I also removed the return; in the method once, but that doesn't fix it either.
How do I make this whole thing work?
The error happens because the method f() is void, meaning: it doesn't return any value that can be added to the ArrayList.
The answer of invoking f() is stored in the ArrayList passed as a parameter to f, you should probably use that ArrayList to add all of its elements to Lists. Something like this:
List<String> lists = new ArrayList<String>();
for (String list : words) {
list.trim();
ArrayList<String> answer = new ArrayList<String>();
f(list, "", answer);
lists.addAll(answer);
}
Your method header for F needs to look like this:
public String f(String s, String anagram, ArrayList<String> array)
And then you return a String value to add to that ArrayList you are using.
Your function definition for f() shows the return value of type void. So looking at your code you're attempting to do this:
Lists.add(void);
which is obviously illegal.
Your choice really is to have the ArrayList declared in a greater scope.
private List<String> anagrams;
public void f(String s, String anagram) {
...
anagrams.add(anagram);
...
}
....
for(String List : words) {
//takes values from old array list
anagrams = new ArrayList<String>();
List.trim();
f(list,"");
Lists.add(anagrams); //this is where it doesn't work
}

Print ArrayList

I have an ArrayList that contains Address objects.
How do I print the values of this ArrayList, meaning I am printing out the contents of the Array, in this case numbers.
I can only get it to print out the actual memory address of the array with this code:
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i));
}
list.toString() is good enough.
The interface List does not define a contract for toString(), but the AbstractCollection base class provides a useful implementation that ArrayList inherits.
Add toString() method to your address class then do
System.out.println(Arrays.toString(houseAddress));
From what I understand you are trying to print an ArrayList of arrays and one way to display that would be
System.out.println(Arrays.deepToString(list.toArray()));
since you haven't provide a custom implementation for toString() method it calls the default on which is going to print the address in memory for that object
solution
in your Address class override the toString() method like this
public class Address {
int addressNo ;
....
....
...
protected String toString(){
return Integer.toString(addressNo);
}
now when you call
houseAddress.get(i) in the `System.out.print()` method like this
System.out.print( houseAddress.get(i) ) the toString() of the Address object will be called
You can simply give it as:
System.out.println("Address:" +houseAddress);
Your output will look like [address1, address2, address3]
This is because the class ArrayList or its superclass would have a toString() function overridden.
Hope this helps.
assium that you have a numbers list like that
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
if you print the list
//method 1
// Conventional way of printing arraylist
for (int number : numbers) {
System.out.print(number);
}
//method 2
// Lambda Expression to print arraylist
numbers.forEach((Integer value) -> System.out.print(value));
//method 3
// Lambda Expression to print arraylist
numbers.forEach(value -> System.out.print(value));
//method 4
// Lambda Expression (method reference) to print arraylist
numbers.forEach(System.out::print);
Are you saying that ArrayList is storing addresses of arrays because that is what is returning from the toString call, or because that's actually what you're storing?
If you have an ArrayList of arrays (e.g.
int[] arr = {1, 2, 3};
houseAddress.add(arr);
Then to print the array values you need to call Arrays.deepToString:
for (int i = 0; i < houseAddress.size(); i++) {
System.out.println(Arrays.deepToString(houseAddress.get(i)));
}
public void printList(ArrayList<Address> list){
for(Address elem : list){
System.out.println(elem+" ");
}
}
I am not sure if I understood the notion of addresses (I am assuming houseAddress here), but if you are looking for way a to print the ArrayList, here you go:
System.out.println(houseAddress.toString().replaceAll("\\[\\]", ""));
Since Java 8, you can use forEach() method from Iterable interface.
It's a default method. As an argument, it takes an object of class, which implements functional interface Consumer. You can implement Consumer locally in three ways:
With annonymous class:
houseAddress.forEach(new Consumer<String>() {
#Override
public void accept(String s) {
System.out.println(s);
}
});
lambda expression:
houseAddress.forEach(s -> System.out.println(s));
or by using method reference:
houseAddress.forEach(System.out::print);
This way of printing works for all implementations of Iterable interface.
All of them, gives you the way of defining how the elements will be printed, whereas toString() enforces printing list in one format.
Simplest way to print an ArrayList is by using toString
List<String> a=new ArrayList<>();
a.add("111");
a.add("112");
a.add("113");
System.out.println(a.toString());
Output
[111, 112, 113]
Put houseAddress.get(i) inside the brackets and call .toString() function: i.e Please see below
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print((houseAddress.get(i)).toString());
}
This helped to me:
System.out.println(Arrays.toString(codeLangArray.toArray()));
public static void main(String[] args) {
List<Moyen> list = new ArrayList<Moyen>();
Moyen m1 = new Moyen();
m1.setCodification("c1");
m1.setCapacityManager("Avinash");
Moyen m2 = new Moyen();
m2.setCodification("c1");
m2.setCapacityManager("Avinash");
Moyen m3 = new Moyen();
m3.setCodification("c1");
m3.setCapacityManager("Avinash");
list.add(m1);
list.add(m2);
list.add(m3);
System.out.println(Arrays.toString(list.toArray()));
}
You can use an Iterator. It is the most simple and least controvercial thing to do over here. Say houseAddress has values of data type String
Iterator<String> iterator = houseAddress.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
Note : You can even use an enhanced for loop for this as mentioned by me in another answer
if you make the #Override public String toString() as comments,
you will have the same results as you did.
But if you implement your toString() method, it will work.
public class PrintingComplexArrayList {
public static void main(String[] args) {
List houseAddress = new ArrayList();
insertAddress(houseAddress);
printMe1(houseAddress);
printMe2(houseAddress);
}
private static void insertAddress(List address)
{
address.add(new Address(1));
address.add(new Address(2));
address.add(new Address(3));
address.add(new Address(4));
}
private static void printMe1(List address)
{
for (int i=0; i<address.size(); i++)
System.out.println(address.get(i));
}
private static void printMe2(List address)
{
System.out.println(address);
}
}
class Address{
private int addr;
public Address(int i)
{
addr = i;
}
#Override public String toString()
{
Integer iAddr = new Integer (addr);
return iAddr.toString();
}
}
You can even use an enhanced for loop or an iterator like:
for (String name : houseAddress) {
System.out.println(name);
}
You can change it to whatever data type houseAddress is and it avoids unnecessary conversions
Make sure you have a getter in House address class and then use:
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i)**.getAddress()**);
}
you can use print format if you just want to print the element on the console.
for(int i = 0; i < houseAddress.size(); i++) {
System.out.printf("%s", houseAddress.get(i));
}
Assuming that houseAddress.get(i) is an ArrayList you can add toString() after the ArrayList :
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i).toString());
}
A general example:
ArrayList<Double> a = new ArrayList();
a.add(2.);
a.add(32.);
System.out.println(a.toString());
// output
// [2.0, 32.0]
This is a simple code of add the value in ArrayList and print the ArrayList Value
public class Samim {
public static void main(String args[]) {
// Declare list
List<String> list = new ArrayList<>();
// Add value in list
list.add("First Value ArrayPosition=0");
list.add("Second Value ArrayPosition=1");
list.add("Third Value ArrayPosition=2");
list.add("Fourth Value ArrayPosition=3");
list.add("Fifth Value ArrayPosition=4");
list.add("Sixth Value ArrayPosition=5");
list.add("Seventh Value ArrayPosition=6");
String[] objects1 = list.toArray(new String[0]);
// Print Position Value
System.err.println(objects1[2]);
// Print All Value
for (String val : objects1) {
System.out.println(val);
}
}
}
JSON
An alternative Solution could be converting your list in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the toString(). Additionaly it works for any other Object or Collection on the fly.
Example using Google's Gson:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
...
public static void printJsonString(Object o) {
GsonBuilder gsonBuilder = new GsonBuilder();
/*
* Some options for GsonBuilder like setting dateformat or pretty printing
*/
Gson gson = gsonBuilder.create();
String json= gson.toJson(o);
System.out.println(json);
}
Add toString() method to your class
houseAddress.forEach(System.out::println);
Consider using an "Enhanced for loop" I had to do this solution for a scenario in which the arrayList was coming from a class object
changing the String datatype to the appropriate datatype or class object as desired.
ArrayList<String> teamRoster = new ArrayList<String>();
// Adding player names
teamRoster.add("Mike");
teamRoster.add("Scottie");
teamRoster.add("Toni");
System.out.println("Current roster: ");
for (String playerName : teamRoster) {
System.out.println(playerName);
// if using an object datatype, you may need to use a solution such as playerName.getPlayer()
}

Categories