how to iterate through an object's list? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm currently facing this problem in Java, lets say I have a class ListOfTasks:
public class ListOfTasks {
private Point startingPoint;
ArrayList<Task> tasks;
}
In another class, I want to iterate through the array list tasks directly by calling ListOfTasks, and not by retrieving tasks first and then iterate through it.

You can do this by implementing Iterable to return the iterator of the array list:
public class ListOfTasks implements Iterable<Task> {
private Point startingPoint;
ArrayList<Task> tasks;
public Iterator<Task> iterator() {
return tasks != null ? tasks.iterator() : Collections.emptyIterator();
}
}
You can then iterate using a for-each
ListOfTasks list = new ListOfTasks();
// add some tasks, etc...
for (Task task : list) {
// use task
}
// or
list.forEach(task -> {
// use task
});

there are many ways to do that:--
Write GETTER/SETTER inside ListOfTasks POJO.
public class ListOfTasks {
private Point startingPoint;
ArrayList<Task> tasks = new ArrayList<>();
GETTER/SETTER
}
then
ListOfTasks list = new ListOfTasks();
for(int i=0 ;i<list.getTask().size();i++){
list.getTasks().get(i);
}

Something like this should work, if I understand your question:
for (int i = 0; i < listOfTasksObject.tasks.size(); i++) {
Task task = listOfTasksObjects.tasks.get(i);
// Now you can work with task...
}

The approach you are taking is wrong, because the responsibility of the property "tasks" is owned by the class ListOfTasks.
So you have to change the approach, and iterate through the set of ListOfTasks instances you have in the other class and call a method, let's say
public Task findTask() {
// do something here to find the Task you were looking for, or return null
}
so the other class should look like this:
List<ListOfTasks> lists = new ArrayList<>();
// populate list here ...
Task found = lists.stream().filter(x => x.findTask()).filter(x => x != null).findAny().orElse(null);

Just dont expose getter for tasks.
create a method in ListOfTasks class like :
public Task get(int index){
return list.get(index);
}
public int size(){
return list.size();
}
now use ListOfTasks like this
for(int i=0 ;i<listOfTasks.size();i++){
// now access Task like this
listOfTasks.get(i);
}

Related

Java 8 Stream | Add a value of the stream to another List/Collection without using foreach or any terminal Operation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So far i tried to add values from a stream to a list with peek() but later I found out that peek() is only used "to support debugging, where you want to see the elements as they flow past a certain point in a pipeline".
Now my question is whats the coding-convention here ?
Do I map it in a second stream or can I map it one String like my Code with Peek() ?
final int range = 9;
List <String> help = new ArrayList<String>();
//random numbers to fill help
for(int i = 5;i< range;i++)
{
help.add(String.valueOf(i+(i*2)+(i*(i+2))) );
}
List<Test> others = new LinkedList<>();
List<Test> tests = help.stream().map(s-> new Test(s,(int) Integer.valueOf("10")))
.peek(t->System.out.println(t.getText()))
.peek(t-> others.add(t)).collect(Collectors.toList());
The class Test looks like this:
public class Test
{
String text;
int id;
public Test(String text, int id) {
this.text = text;
this.id = id;
}
public String getText() {
return text;
}
public int getId() {
return id;
}
}
You could add that functionality to the lambda in the mapping part:
List<Test> tests = help.stream().map(
s-> {
Test t = new Test(s,(int) Integer.valueOf("10")));
System.out.println(t.getText());
others.add(t)
return t;
}
.collect(Collectors.toList());
That simply moves your extra steps into an existing step, avoiding any further loops etc

Java: LinkedList [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
is there a way to say that if you reach the null reference, then do something ?
e.g. if i have a linkedlist with just one object and after this comparison, if you reached null then do something...
for(int i = 0; i < queue.size(); i++) {
if (queue.get(i).compareTo(newitem) == -1) {
continue;
}
}
for instance another if-clause in the loop saying
if (queue.equals(null)) {
queue.add(newitem);
}
this is btw the linkedlist
public OrderedQueue() {
queue = new LinkedList<T>(); // generate an empty queue
}
You can always check that the object in your list is null to do a special operation:
for(Element e : queue) {
if(e == null) {
// special operation
} else {
// normal operation
}
}
Also use a for-each loop to iterate over elements.
In your case, using the get(i) method is not very efficient on a LinkedList. Using a for each allows you to abstract the actual type of the Iterable you are iterating over.
Replace everything with:
if (!queue.contains(newItem)) {
queue.add(newItem);
}

Access a linked list through a method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In this method I'm suppose to remove all zeroes from a linkedlist but I'm not sure how to access the linked list. I am not allowed to change the parameters of the method but I can change the return. How can I access the linkedlist to modify it?
public domino removeZero() {
// ****** student exercise
return this;
}
This is the line that calls the method:
train = train.removeZero();
The name of the class is domino.
Here is the complete program http://pastebin.com/EwNJj9mV
You can use some getter setter method
like store your linkedlist in one different class's static variable and than in your method get that static variable's value.
import java.util.LinkedList;
public class linkedListStorage {
private static LinkedList linkedList;
public static LinkedList getLinkedList() {
return linkedList;
}
public static void setLinkedList(LinkedList linkedList) {
linkedListStorage.linkedList = linkedList;
}
}
now when you get your linkedlist put it via setter method
import java.util.LinkedList;
class JunitTest {
public static void main(String[] args) {
// set linked list to storage class's variable
linkedListStorage.setLinkedList(your linked list variable);
}
}
now use your linked list in your method
public domino removeZero() {
// ****** student exercise
// get your linked list from storage class
LinkedList ll = linkedListStorage.getLinkedList();
return this;
}
I suspect you need to learn some basics about object oriented programming and then re-ask the question. The method you have included in your question (removeZero) is a member of a class (domino) that has fields you can access inside the method. In other words removeZero has access to the linked list because it's a method of the linked list object.
In this case the code would be something like:
public domino removeZero() {
domino first = null;
for (domino current = this; current.next != null; current = current.next) {
if (current.spot1 == 0 || current.spot2 == 0) {
if (current.back != null)
current.back.next = current.next;
if (current.next != null)
current.next.back= current.back;
} else if (first == null) {
first = current;
}
}
return first;
}
By the way, you should tell your teacher to use capital letters to start class names. It should be called Domino, not domino.

Change method return type to List<String> java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my application I have a method fetchJSONChild() as below:
public List<String[]> fetchJSONChild(){
final List<String> child;// = new ArrayList<String>();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
String data1 = "1,2,3";
//String[] parts = new String[3];
child = new ArrayList<String>(Arrays.asList(data1.split(",")));
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
return child;
}
In this method I have created a list and put splitted string items on it but when I return this list, I am getting an error at this line return child; as below:
Change method return type to List<String>
How can I resolve it?
Thanks
As mentioned by others you have to change List<String[]> to List<String>. You can't assign a new ArrayList to child because you declared it to be final. Besides that your code is really messed up and your Thread makes no sense. You should instead do something like this:
// Don't use a thread in your method.
public List<String> fetchJSONChild(){
final String data1 = "1,2,3";
final List<String> child = new ArrayList<String>(Arrays.asList(data1.split(",")));
return child;
}
// Call your method in a thread elsewhere
new Thread(new Runnable() {
#Override
public void run() {
// Since the method is not static, you need a reference to an object which declares this method.
final List<String> chils = yourObject.fetchJSONChild();
// Do something with your list
}
}).start();
Change:
public List<String[]> fetchJSONChild(){
to:
public List<String> fetchJSONChild(){
You're trying to return an ArrayList<String> but the return type of your method is List<String[]>. Notice the [], your method wants to return a list of arrays of strings, which is different from a list of strings.
Just change your return type to List<String>:
public List<String> fetchJSONChild()
Return type should be List<String> That's it
You've defined in your Signature a List<String[]>, so a list of String arrays.
But the List you instantiate is actually a List of Strings.
Please not that an ArrayList actually doesn't mean that it contains Arrays. (See https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html)
Either you change your method signature to public List<String> fetchJSONChild()
or you have to create Arrays of Strings within your method.
Best Regards
Datatype of child is List<String>. However return type of function is List<String[]> causing type mismatch.
Change return type of function to List<String> (and not List<String[]>) and it may work.
There is no point in having a multithreaded design for this program. Most likely when you fix the compilation problems that others mentioned your method will always return an empty List. I would suggest not to do any mutithreading in this case.

Traverse List recursively of java class [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have one class release it contain list object of its self now i want that recursive list to get parsed and want it in one list.
Here is my class :
public class OnTimeNowRelease implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
int id;
String name;
String can_modify;
String start_date;
String due_date;
String velocity_start_date;
String release_notes;
String status;
String is_active;
String release_type;
List<OnTimeNowRelease> children ;
getter setter//
}
How can I traverse List of children up to nth level? its like traversing tree..if object does not have child its value is children = null
This is simple Traversal example, which you mostly see in LinkedList or Trees.
public void fetchAllChildren(OnTimeNowRelease root, List<OnTimeNowRelease> childList){
// if the parent is not defined, nothing to do
if(root == null){
return;
}
//add the parent to the list. Since java is Reference by Value, the list can be used for recursively adding all the descending elements
childList.add(root);
if(root.children !=null && !root.children.isEmpty()){
for(OnTimeNowRelease children : root.children){
//simple recursive solution add all the children and their children and so on....
fetchAllChildren(root.children, childList);
}
}
}
You could try something like:
public List<OnTimeNowRelease> flattenLists(OnTimeNowRelease obj) {
List<OnTimeNowRelease> result = new ArrayList<OnTimeNowRelease>();
List<OnTimeNowRelease> children = obj.getChildren();
if (children==null || children.isEmpty()) {
return result;
} else {
for (OnTimeNowRelease child : children) {
result.addAll(flattenLists(child));
}
}
return result;
}
This will iterate over all the children of each List and recursively add each of their child elements to one big list. You only have to initially call it with the root element once.
I don not know what yo want exactly: put in list all items in the tree to print it? move the childs of one item to his parent?
In the first case you can add a recoursive function to the class who obtain it:
public List<OnTimeNowRelease> obtainDescendants() {
// create a list for the childs
List<OnTimeNowRelease> items = new ArrayList<OnTimeNowRelease>();
// add myself
items.addAll(this);
if(children != null) {
// add my childs and his childs to the list
for(OnTimeNowRelease child : this.children) {
items.addAll( child.obtainDescendants() );
}
}
return items;
}
In the seconds case you can do something like
public void inherintChilds() {
if( children == null) {
return;
}
for(OnTimeNowRelease child : this.children) {
if( child.children != null) {
// take the childs
this.children.addAll(child.children);
// quit to my child
child.children = null;
}
}
}

Categories

Resources