How to pass multiple values to a single parameter for a particular method in java.
e.g. suppose i have a method with single parameter 'childname', that gets names of all the children in a family.
Now how can i pass multiple values to this parameter to get all different names.
public String getChildrenNames(String childname)
{
children= childname+ familyName;
return children;
}
You would typically implement this using either an Array, or a Collection.
eg:
public String[] getNamesOfChildren()
or
public Collection<String> getNamesOfChildren()
As people say you need to pass them as an Array, so your code should be like this:
String familyName = "Family";
public String[] getChildrenNames(String[] childnames)
{
String[] result = new String[childnames.length];
for(int i=0; i<childnames.length; i++)
{
result[i] = childnames[i] + " " +familyName;
}
return result;
}
public void main()
{
String[] childnames = {"Name1", "Name2", "Name3"};
String[] childnamesAux = getChildrenNames(childnames);
}
With this your childnamesAux variable should have: {"Name1 Family", "Name2 Family", "Name3 Family"}
If you can't change the signature of your method, then you can use concatenation, then in your method you can split this parameter for example :
String childname = firstname + "," + lastname;
getChildrenNames(childname);
so you can split this parametter to get multiple names,
String[] spl = childname.split(",");
But there are better ways then this, if you can change the signature of your method, so you can create a method which can take an array or list of names instead :
public String getChildrenNames(String...childnames) {
or
public String getChildrenNames(Lis<String> childnames) {
You can even create an Object for example :
class Person{
private String firstname;
private String lastname;
//getters and setters
}
Then your method should take an array or a list of Person Object :
public String getChildrenNames(List<Person> childname) {
You can try this
public static String child(String... name){
String[] array=name;
String tem;
if(name.length==1)
return name[0];
for(int counter=0; counter<array.length;counter+=2){
array[0]=name[counter]+name[counter+1];
}
tem=array[0];
return tem;
}
now if you call it
child("Paul","walker");
the output will be
Paul Walker
hope this helped
you can use var args like below
public String getChildrenNames(String... childname)
{
for(String s:childname)
{
children= childname+ s;
}
return children;
}
example
public class Test {
public static void main(String[] args) {
System.out.println(tes("s","d","s"));
}
static String tes(String... x)
{
String y="";
for(String s:x)
{
y=y+s;
}
return y;
}
}
output: sds
Related
Im trying to make a program that allows the client to input a String. The string length should have 3 characters only and should contain the letters .
My program have to pass through this table and check what this string refers to..
Let's say the client passed this String "AUG", my program should show the name of this String which is "Met".
I made a code, and it worked but it has more then 15 if else-if condition.
My question is : Is there any other way to do it without using if else-if (or switch).
And does polymorphism work in this case ?
Have a look at HashMap
You can build your table with:
Map<String, String> table = new HashMap<>();
table.put("AUG", "Met");
table.put(...);
Then access your table using the user's input:
if(table.containsKey(input)){
return table.get(input);
}
I think I'd go about it with an enum personally (provided performance wasn't a significant concern):
public enum Abbreviations {
Ala("GCU", "GCC", "GCA", "GCG"),
Arg("CGU", "CGC", "CGA", "CGG", "AGA", "AGG")
// ...
;
private final List<String> codons;
private Abbreviations(final String... codons) {
this.codons = Arrays.asList(codons);
}
public boolean contains(final String codon) {
return this.codons.contains(codon);
}
}
And then you can find their matching from the String using something like:
public String find(final String codon) {
for (final Abbreviations abb : Abbreviations.values()) {
if (abb.contains(codon)) {
return abb.name();
}
}
throw new IllegalArgumentException("Unknown codon: '" + codon + "'");
}
You could try an Object Oriented Aproach:
//This is your representation of Codon
//Which has a name e.g. Alanine and an Abreviation object.
public class Codon {
private String name;
private Abreviation abreviation;
public Codon(String name, Abreviation abreviation) {
this.name = name;
this.abreviation = abreviation;
this.abreviation.addCodon(this);
}
#Override
public String toString() {
return "Codon [name=" + name + ", abreviation=" + abreviation + "]";
}
}
import java.util.ArrayList;
import java.util.List;
// This is a representation of an abreviation object
// Which has an abreviation: ALA;
// and the name of the abreviation "Alanine".
public class Abreviation {
private String abreviation;
private String name;
private List<Codon> codons = new ArrayList<>();
public Abreviation(String abreviation, String name) {
super();
this.abreviation = abreviation;
this.name = name;
}
public boolean addCodon(Codon codon) {
return this.codons.add(codon);
}
#Override
public String toString() {
return "Abreviation [abreviation=" + abreviation + ", name=" + name + "]";
}
}
// Here is your program, where it's being build all the Codons structure with your respective Abbreviation.
public class App {
public static void main(String[] args) {
// This is abreviation, it'll will associated with the codon
Abreviation alanine = new Abreviation("Ala", "Alanine");
// Here it's being build the codon CGU, which has abreviation alanine
Codon GCU = new Codon("GCU", alanine);
// Then using toString method it prints what have been done
System.out.println(GCU);
}
}
You can put all of your codons into a List, so you can search and retrieve then.
I have a list of objects "SaleItem". they are all objects of the same class. each object has a String field "name" and an int field "value". I want to see if one of the objects contains a name. It seems that I can't use the "contains" method to do this. I see two solutions. one is to iterate through all the objects to check if one has said name:
for (SaleItem item: myList) {
if (item.getName() == "banana") {
// do stuff
}
}
The other solution would be to create a new list of Strings from "myList" and use the contains method on that:
ArrayList<String> nameList = new ArrayList<>();
for (SaleItem item: myList) {
nameList.add(item.getName());
}
if (nameList.contains("banana")) {
// do stuff
}
I imagine the first method would be most efficient if I'm only doing it once, and the second would be more efficient if I'm doing it many times. Being a bit of a newbie without a formal education, I don't know what's proper in this situation.
Since SaleItem.getName() returns a string, you should be able to use "contains" method.
It seems like you have initialized the ArrayList or the SaleItem object incorrectly.
public class TestApp {
public static void main(String[] args) {
List<SaleItem> list = new ArrayList<SaleItem>();
SaleItem s1 = new SaleItem();
s1.setName("banana");
s1.setValue(1);
SaleItem s2 = new SaleItem();
s2.setName("apple");
s2.setValue(2);
list.add(s1);
list.add(s2);
for (SaleItem item: list) {
if (item.getName().contains("banana")) {
System.out.println("Pass");
}
}
}
}
class SaleItem {
private String name;
private int value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
Try with this code
public class SaleItem {
private String itemName;
public String getItemName() {
return itemName;
}
public SaleItem setItemName(String itemName) {
this.itemName = itemName;
return this;
}
#Override
public String toString() {
return "[SaleItem : { itemName = " + this.getItemName() + " }]";
}
public static void main(String[] args) {
ArrayList<SaleItem> nameList = new ArrayList<>();
nameList.add(new SaleItem().setItemName("banana"));
nameList.add(new SaleItem().setItemName("grape"));
nameList.add(new SaleItem().setItemName("watermelon"));
nameList.add(new SaleItem().setItemName("orange"));
nameList.add(new SaleItem().setItemName("guava"));
for (SaleItem item : nameList) {
if (item.toString().contains("banana")) {
// Do this
}
}
}
}
A List's .contains method isn't magical, it will generally just loop through the elements checking for equality, O(n) linear performance.
Your first solution is probably fine.
If you really did expect repeated access and wanted better than linear performance on subsequent lookups, you'd probably want to construct a Map<String,SaleItem>, or a Set<String> depending on what you wanted to do with it. But those solutions would normally only work on exact matches. Once you need case-insensitive matches, they have to be TreeMap or TreeSet with a case-insensitive comparator. And if you want partial matching (like using String.contains() or a regular expression), you'd want to go back to a linear search.
But don't do any of that unless you have to. Keep it simple.
I have list of string data that are not change during any operation inside my program. But i need to access those data in several places by using key.
As a example: (1,ANN)(2,ALEX)(3,ANDROW)
Is there any way to store these data in separate class.Can I use java enum for this. thank you
With the use of enum you can implement something like below:
public enum Name {
ONE {
#Override
public String getName() {
return "ANN";
}
},
TWO {
#Override
public String getName() {
return "ALEX";
}
},
THREE {
#Override
public String getName() {
return "ANDROW";
}
};
public abstract String getName();
}
Then you can get the the names :
System.out.println(Name.ONE.getName());
This is really a good candidate for using Map. Where you can use your numbers as keys and String's as values.
https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
Map<Integer, String> map = new HashMap<Integer,String>();
Map<Integer,String> is one option and if key is also constant you could define string variable like
public static final string ONE = "ANN";
public static final string TWO = "ALEX";
A different way to use enums to define a statically mapping:
public enum Names {
ONE("ANN"),
TWO("ALEX"),
THREE("ANDREW");
private final String name;
private Names(String name){
this.name=name;
}
public String getName() {
return this.name;
}
}
This is only applicable to real-static values (change to values does mean a code change), but you can easily define multiple properties as well.
You can do the following:
import java.util.HashMap;
public class Main {
static HashMap<Integer,String>data = new HashMap<>();
public static void main(String[] args) {
// write your code here
data.put(data.size(),"ALEX"); // if you want 1-based indexing,
data.put(data.size(),"ANDROW"); // then use data.size()+1
data.put(data.size(),"ANN"); // instead of data.size()
for (int i = 0; i<data.size(); i++){
System.out.println(i+" : "+data.get(i)); // use i+1 if 1-based indexing
}
}
}
I'm using eclipse and I'm trying to sort a text file with about 40 lines that look like this:
1,Terminator,1984,Schwarzenegger
2,Avatar,2009,Worthington
3,Avengers,2012,Downey
4,Starwars,1977,Hammill
5,Alien,1979,Weaver
I want sort them alphabetically by the second field so that the text file is altered to look like this:
5,Alien,1979,Weaver
2,Avatar,2009,Worthington
3,Avengers,2012,Downey
4,Starwars,1977,Hammill
1,Terminator,1984,Schwarzenegger
I'm fairly certain I should be doing something involving tokenizing them (which I've already done to display it) and a BufferedWriter but I can't for the life of me think of a way to do it by the second or third field and I feel like I'm missing something obvious.
You will first of course need to read a file, which you can learn how to do here.
Java: How to read a text file
This example will provide several ways you may write the file once you have sorted your data.
How do I create a file and write to it in Java?
As for sorting, I recommend creating a class Movie, which would look similar to
public class Movie implements Comparable<Movie> {
private String name;
private String leadActor;
private Date releaseDate;
public Movie(String name, String leadActor, String releaseDate) {
}
#Override
public int compareTo(Movie other) {
}
}
Ill leave it to you fill in the rest of the constructor and compareTo method. Once you have your compareTo method you will be able to call Collections.sort(List list) passing your list of Movie.
Here are some resources on implementing Comparable.
http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
Why should a Java class implement comparable?
Your comparator
class SampleComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
String array1[] = o1.split(",");
String array2[] = o2.split(",");
return array1[1].compareTo(array2[1]);
}
}
Your Sorting
String [] lines= {"1,Terminator,1984,Schwarzenegger",
"2,Avatar,2009,Worthington",
"3,Avengers,2012,Downey",
"4,Starwars,1977,Hammill",
"5,Alien,1979,Weaver"};
List<String> rowList = new ArrayList<String>(Arrays.asList(lines));
Collections.sort(rowList, new SampleComparator());
for (String string : rowList) {
System.out.println(string);
}
Your Output
5,Alien,1979,Weaver
2,Avatar,2009,Worthington
3,Avengers,2012,Downey
4,Starwars,1977,Hammill
1,Terminator,1984,Schwarzenegger
If you have any doubt on this let me know..
The String class has a very helpful static method called "split". All you do is call split and put it in the delimiter and it gives back a String array with the split up string.
Here's an example:
String line = "How,Now,Brown,Cow";
String[] splitLine = line.split(",");
for(String l: splitLine)
{
System.out.println(l);
}
The above code would print the following:
How
Now
Brown
Cow
Hopefully you can use this and adapt it to your problem.
Good luck!
What you want to do is to use java.util.Comparator and Collections.sort. More on this can be found: http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
Following #Tyler answer. You can have a default implementation in the Movie class and additional sort orders that you can implement by calling Collections.sort(movieList, new MyComparator()); Here comes an example of both.
package com.stackoverflow;
public class Movie implements Comparable<Movie> {
private String name;
private String leadActor;
private String releaseDate;
public Movie(String name, String leadActor, String releaseDate) {
this.name = name;
this.leadActor = leadActor;
this.releaseDate = releaseDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLeadActor() {
return leadActor;
}
public void setLeadActor(String leadActor) {
this.leadActor = leadActor;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
#Override
public int compareTo(Movie other) {
return getName().compareTo(other.getName());
}
}
And if you want to make your own comparator called on your collection:
package com.stackoverflow;
import java.util.Comparator;
public class MyComparator implements Comparator<Movie> {
#Override
public int compare(Movie o1, Movie o2) {
return o1.getLeadActor().compareTo(o2.getLeadActor());
}
}
Try like this :--
ArrayList ar=new ArrayList();
String [] arr=new String[10];
int i=0;
try {
Scanner sc=new Scanner(file);
while (sc.hasNextLine())
{
String ss=sc.nextLine();
i=i+1;
arr[i]=ss;
}
ar.add(arr[5]);
ar.add(arr[2]);
ar.add(arr[3]);
ar.add(arr[4]);
ar.add(arr[1]);
System.out.println(ar);
}
This solution uses Java 8 APIs.
You don't really need to have an explicit implementation of Comparator or create a Comparable class. Using Comparator.comparing with lambda we can elegantly sort lines by custom key.
import java.io.IOException;
import java.nio.file.*;
import java.util.Comparator;
import java.util.stream.Stream;
public class FileSortWithStreams {
public static void main(String[] args) throws IOException {
Path initialFile = Paths.get("files/initial.txt");
Path sortedFile = Paths.get("files/sorted.txt");
int sortingKeyIndex = 1;
String separator = ",";
Stream<CharSequence> sortedLines =
Files.lines(initialFile)
.map(s -> s.split(separator))
.sorted(Comparator.comparing(s -> s[sortingKeyIndex]))
.map(s -> String.join(separator, s));
Files.write(sortedFile, sortedLines::iterator, StandardOpenOption.CREATE);
}
}
i want to split the mProductType is one list and mRetailerid is another list.how can i get it ????
public class RetailerNames implements Serializable{
private String mProductType;
private String mRetailerid;
public String getmProductType() {
return mProductType;
}
public void setmProductType(String mProductType) {
this.mProductType = mProductType;
}
public String getmRetailerid() {
return mRetailerid;
}
public void setmRetailerid(String mRetailerid) {
this.mRetailerid = mRetailerid;
}
#Override
public String toString() {
return mProductType + "," +
mRetailerid ;
}
I have used below code :
ArrayList<RetailerNames> retailerNamesList = (ArrayList<RetailerNames>) getIntent().getExtras().getSerializable("ProductsDetailsDescriptionPage");
System.out.println("The retailer details are"+" "+retailerNamesList);
Now my current output is:
The retailer details are [Krish,48, Danesh,47]
But i want to get the one list like [Krish,Danesh] .and [48,47] is separate another list.How can i do ???
please give me solution ???
please give me a ideas to split the array list to separate list???
ArrayList list = new ArrayList();
Iterator<RetailerNames > retaileriterator = retailerNamesList.iterator();
while(retaileriterator.hasNext()){
id=retaileriterator .next().getmRetailerid();
System.out.println(id);
list.add(id);
}
System.out.println(list);
In my condition getLocationDetails return arraylist
and LocationDetails is POJO same like your class RetailerNames
Iterator<LocationDetails> it= getUserLocationsWrapper.getLocationDetails().iterator();
while(locationCitiDetailsItr.hasNext()){
locationCitiDetailsItr.next().getCity());
}
same i think try this one
Iterator<RetailerNames > retaileriterator = retailerNamesList.iterator();
while(retaileriterator.hasNext()){
Object id=retaileriterator .next().getmRetailerid();
//add this id into another list
//same RetailerNames
}
use nested array
Put [Krish,48] is one list and
[damesh,47] in another list and put both the list in one main array list
Use like this
public class RetailerNames implements Serializable{
private String mProductType;
private String mRetailerid;
public String getmProductType() {
return mProductType;
}
public void setmProductType(String mProductType) {
this.mProductType = mProductType;
}
public String getmRetailerid() {
return mRetailerid;
}
public void setmRetailerid(String mRetailerid) {
this.mRetailerid = mRetailerid;
}
#Override
public String toString() {
return + mProductType + ","
+ mRetailerid +; //Remove "[" this..
}
And,
ArrayList<RetailerNames> retailerNamesList = (ArrayList<RetailerNames>) getIntent().getExtras().getSerializable("ProductsDetailsDescriptionPage");
System.out.println("The retailer details are"+" "+retailerNamesList);
Now try
Object temp[]=retailerNamesList.toArray();
String[] values=temp.toString().split(",");
String names=values[0];
String names=values[1];