I'm unsure how to do this,
Say I have this in ,
List<SetOfStuff> example = [[a,b,c],[1,2,3],[x,y,z]];
return example;
Is there a way for me to only return the first element of each set, so for example.
return [[a],[1],[x]];
or even better
return [a,1,x];
Thanks for the help
Essentially, you are defining a set within a list (I'm guessing that SetOfStuff is some sort of Set) with this line:
List<SetOfStuff> example = [[a,b,c],[1,2,3],[x,y,z]];
You need to first get an element from example
using the List's get() method, and then get the first element the result you are returned from the List's get(). To access every element inside the List (so every Set), you'll need some sort of loop. Below is semi-pseudocode on how to do this. It depends on how you can access elements inside SetOfStuff.
List<Object> firstElements = new List<Object> (); // normally, using Object is not a great idea, but I don't know much about the data in example. Change this accordingly
for (int i = 0; i < example.size(); i++){ // this iterates over every element in the list
firstElements.add(example.get(i).getFromSet(0)); // in this, I assume that getFromSet(0) gets the first element from the SetOfStuff object
}
This is the basic format of what you're looking for. Let me know if you have any questions.
If SetOfStuff has structure, and you state that it is a POJO, then give it a getId()
method if it doesn't have one already. Then, start off with
public List<SetOfStuff.ID> extractIds(List<SetOfStuff> stuffList) {
List<SetOfStuff.ID> ids = new ArrayList<>() // Java 7.
for((SetOfStuff stuff: stuffList) {
ids.add(stuff.getId());
}
return ids;
}
Use the actual type of SetOfStuff.ID
if necessary. Consider a functional programming library with a transform method, and go to Java 8 lambdas when you can.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.