Getting an object variable from List in C# - java

I have class with variables:
public class Items {
public string name;
public string ID;
}
and I have second class when I have List of object of first class
public class MyClass {
public Items cheese;
public List <Items> listOfItems = new List ();
listOfItems.Add (cheese); // I know it should be in method or something but it's just an example
}
and I want get the name of the cheese, but using my list, because I have above 20 items in my list.
In Java I can do it like:
listOfItems.get(1).name; // 1 is an index
How can I do it in C#?
// Please don't try to improve my

listOfItems[0].name;
Just remember to start counting at 0 ;)
Other than that its works the same way as java, just slightly different syntax

The simple way:
listOfItems[1].name;
If you want a specific item try this:
var name = listOfItems.Find(x => x.ID == "1").name;
"1" is the example "Id" that you search.
Sorry for my english
I hope help you.

Related

Filter Java stream if specific object is a null

I have the object FastFood. In ArrayList there are 10 hotdogs.
public class FastFood {
ArrayList<Hotdog> hotdogs;
boolean isTasty;
}
public class Hotdog {
String name;
Ingredients ingredients;
}
For 9 hotdogs all data is filled.
For 1 hotdog, the object Ingredients is null.
How can I modify below metod to have only these hotdogs, which have filled Ingredients? (I would like to see 9 hotdogs).
public List<Hotdog> convert(Fastfood fastfood) {
List<Hotdog> hotdogs = fastfood.getHotdogs().stream()
.map(this::convertToHotdog)
.collect(Collectors.toList());
Based on comments & question, it looks like convertToHotdog might be something to do with internal conversion of Hotdog which is not shared as a part of question. In that case, below might be useful:
List<Hotdog> hotdogs = fastfood.getHotdogs().stream()
.filter(t->Objects.nonNull(t.getIngredients()))
.map(this::convertToHotdog)
.collect(Collectors.toList());
If you have list of hotdog objects, you can use filter() method, like this:
List<Hotdog> hotdogs = fastfood.getHotdogs().stream()
.filter(hotdog->hotdog.getIngredients()!=null)
.collect(Collectors.toList());
NOTE: I'm assuming that you have getter method for ingredients field in Hotdog class which is called getIngredients()

Java passing a (lambda) function with two arguments

I'm trying to implement a function to read files, but I cannot change the signature of the method. There are a lot of cross references in the code but maybe someone can enlighten me, I have been stuck for 3 days right now. This is for a school assignment.
The first method I'm trying to pass into the function is the following:
public static Purchase fromLine(String textLine, List<Product> products) {
Purchase newPurchase = null;
String[] purchases = textLine.split(",");
int foundBarcode = products.indexOf(getProductFromBarcode(products, Long.parseLong(purchases[0])));
products.indexOf(purchases);
newPurchase = new Purchase(
products.get(foundBarcode),
Integer.parseInt(purchases[1].trim())
);
Somehow I want to pass this function into my import file function.
public static <E> void importItemsFromFile(List<E> items, String filePath, Function<String,E> converter) {
int originalNumItems = items.size();
Scanner scanner = createFileScanner(filePath);
// TODO read all source lines from the scanner,
// convert each line to an item of type E and
// and add each item to the list
while (scanner.hasNext()) {
// input another line with author information
String line = scanner.nextLine();
// TODO convert the line to an instance of E
E newItem = converter.apply(line);
// TODO add the item to the list of items
items.add(newItem);
}
System.out.printf("Imported %d items from %s.\n", items.size() - originalNumItems, filePath);
}
I hope someone can help me and explain how to pass this function into the other function's converter parameter.
Tried to do a lot of research on this topic but I'm still not able to find the answer. Please help me stackoverflow community!:D
You need to declare this like this first inside a 'super - private function'
private Function<String, Purchase> doSomething() {
return textLine -> {
Purchase newPurchase = null;
String[] purchases = textLine.split(",");
int foundBarcode = products.indexOf(getProductFromBarcode(products, Long.parseLong(purchases[0])));
products.indexOf(purchases);
return new Purchase(products.get(foundBarcode), Integer.parseInt(purchases[1].trim())
};
}
Then before calling this importItemsFromFile() method, you declare this function as a variable
Function<String, Purchase> abcFunction = doSomething();
and then call this importItemsFromFile() function like this
importItemsFromFile(items, filePath, abcFunction);
The reason why this works is, lambda operator returns a Functional Interface, here it is "Function", if you pass 3 arguments, you will need a BiFunction<T, U, R> for that.
Thats why these FunctionalInterfaces are sometimes called super private functions, as they are used inside another function.
And Hey give me extra points for this, as I even completed your half written function, and saved your 3 days time.
I am a little lost by the top snippet, but all you need to do is define an implementation of the Function interface. You can do this simply by defining a class that implements the interface or you can specify a lambda that would do the same thing.
Assuming the top code block is what you want in your lambda you would do something like this,
(textLine) ->{
String[] purchases = textLine.split(",");
int foundBarcode = products.indexOf(getProductFromBarcode(
products, Long.parseLong(purchases[0])));
products.indexOf(purchases);
return new Purchase(
products.get(foundBarcode),
Integer.parseInt(purchases[1].trim())
)

Adding to an array list within a class in Java? Beginner

Still learning the basics however I've been stuck on this. I'm trying to add members to a club from the methods I've wrote, but I'm getting an error on the join method..
import java.util.ArrayList;
public class Club
{
private ArrayList<String> memberList;
public Club()
{
memberList = new ArrayList<String>();
}
public void join(String newMember)
{
memberList.add(newMember);
}
}
public class TestClub
{
public TestClub()
{
}
public static void main(String args[]){
Club myClub = new Club();
System.out.println("The club has " +
myClub.numberOfMembers() +
" members.");
myClub.join("Gary", 5, 2019));
}
}
I know I'm missing something, just can't figure out what. I create the club object but it won't let me add to the list. How do I get the object to accept 3 values/arguments?
This line:
myClub.join("Gary", 5, 2019));
You have two closing parentheses. You might want to delete the last one. Also, you have 3 variables, the string, the integer and another integer.
Maybe you want to say:
myClub.join("Gary");
or
myClub.join("Gary, 5, 2019");
Also, you haven't yet implemented the method, numberOfMembers in the Club class, so that will always fail.
myClub.numberOfMembers()
You would need to have a method in Club class that returns the number of members, meaning the memberList size.
1)You have added extra closing ')' also method 'join(String newMember)' has one parameter, the String. You are trying to pass it 3 value :- join("Gary", 5, 2019);
2) Also your arrayList is of type String you can only add String values eg : "Gary" and not Integer eg : 5 or 2019.
You can also redefine method 'joins' like below for adding multiple value in single method call
public void join(String ...newMember)
{
Collections.addAll(memberList, newMember);
}
and change method call as below
myClub.join("Gary", "5", "2019");

How can I make arrays with own objects in Java in Android Studio.

I have a long piece of code that looks like this
Kwas a1 = new Kwas("Kwas Azotowy(V)", "HNO3");
// etc..
Kwas a17 = new Kwas("Kwas FluorkoWodorowy", "HF");
How can I write it as an Array? I tried something like
Kwas[] a = new Kwas[17]
But it didn`t work.
My "Kwas" class looks like the following:
public class Kwas {
String name;
String formula;
public Kwas( String nazwa, String wzor)
{
name = nazwa;
formula = wzor;
}
void setName(String c)
{
name = c;
}
void setFormula(String c)
{
formula = c;
}
public String getName()
{
return name;
}
public String getFormula() {return formula;}
}
You can do this:
List<Kwas> list = new ArrayList<Kwas>();
list.add(a2);
Just implement an ArrayList like this:
ArrayList<Kwas> newArray= new ArrayList<>();
And then:
newArray.add(a2);
newArray.add(a3);
newArray.add(a4);
newArray.add(a5);
newArray.add(a6);
newArray.add(a7);
...
...
Then if you want to get an specific item just write something like this:
newArray.get(1).getName(); //for example
I can't comment yet, so I have to provide it as an answer. Everyone is answering here how OP can construct a List, but no one is actually answering how he can create an array, which is probably very confusing for OP who might now think you can't create arrays of self-defined objects. You definitely can. But I don't know what the problem is.
Kwas[] a1 = new Kwas[17];
is definitely the right syntax. Are you sure you include the class? Can you post the exact code and error?
My guess is that you didn't import your class. In Android Studio, try placing your cursor after Kwas and pressing Ctrl+Space. This should show a dropdown list. Select the first line and press enter. Now it should have added an import to your class.
ArrayList<yourObjectName> arrayName = new ArrayList<yourObjectName>();
Then .add(object) on every object
You can simply type:
ArrayList<ObjectType> arrayName = new ArrayList<ObjectType>();
Adding Elements:
arrayName.add(someObject);
Removing Elements:
arrayName.remove(arrayName.get(someInteger));
Getting Elements:
arrayName.get(someInteger);
PS: Don't forget to import:
import java.util.ArrayList;

Can I put a String in an Arraylist when a object is created?

I want to make a program where you can name a String("weapon" for example)and then add that String to a ArrayList. But without typing it yourself like:
MyArrayList.add(Egg); //for example
So that the new Object automatically add to the Arraylist.
So what I did, I created an Arraylist that will hold the weapon names. I made a method, where you can "make" in the main class a object with the weapon name.But how do i make something that when a object (in the main class)is created, it automatically add it self to the arraylist.
(Sorry for bad explaining, I'm from The Netherlands so... If it's a bad explaining please tell me so i can improve it)
Maybe I completely misunderstand it, but do you want to do something like this?
private ArrayList<YourObject> list;
public YourMainClass(){
list = new ArrayList<YourObject>();
}
public void onAdd(String weaponName){
list.add(new YourObject("weaponName")); // <- this being your issue
}
With YourObject being something like:
public class YourObject
{
private String name;
public YourObject(String n){
setName(n);
}
public void setName(String n){
// Perhaps an if-else to check if n isn't null, nor emtpy?
name = n;
}
public String getName(){
return name;
}
}
Based on my interpretation of your problem, you want to have the user create a weapon name and add it to the ArrayList without having to manually add the code to add it?
A basic way to get String input from a user:
Scanner inputscan = new Scanner(System.in); //reads input from command line
String weapon = inputscan.nextLine(); //waits for user input
MyList.add(weapon);
That way, every time you call the "make" method with that code in it, it will prompt the user to type a weapon name, then the weapon name gets stored in the array.
I think you want to initialize the List with an object in it:
Try using an instance block, like this:
List<String> list = new ArrayList<String>() {{
add("Egg");
}};
Add the command to add the object to the collection in the constructor.( But this ill advise)
You can create an auxiliary class that will create that object and label to the collection.
class WeaponFactory
{
Collection c;
public WeaponFactory(Collection coll){c=coll;}
public Weapon makeWeapon(String text) // Makes sense when the object is not String , like a Weapon class which also contains stats or something
{
Weapon w = new Weapon(text)
c.add(w);
return w;
}
}
class Weapon
{
String name;
public Weapon(String text)
{
name = text;
}
}

Categories