Convert List<List<String>> to String[][] [closed] - java

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 2 years ago.
Improve this question
How might I convert List<List<String>> to String[][]?
I've played around with the solutions provided here but not having much luck.
Any help would be appreciated.

Explanation
You can not just apply outer.toArray(...) because that would give you an array of lists, List<String>[].
You have to first convert all the inner lists before you can collect them into your resulting data structure. There is no utility method available that can do this automatically for you, but it is fairly easy to do it yourself.
Stream API
Streams are a very good candidate for this. Just stream the outer list, convert the inner lists and then use toArray as provided by Stream.
String[][] result = outer.stream() // Stream<List<String>>
.map(inner -> inner.toArray(String[]::new)) // Stream<String[]>
.toArray(String[][]::new);
Traditional loop
You can follow the exact same idea also with a more traditional manual approach where you setup your target outer array, loop over the inner lists, convert them and collect them into your array.
String[][] result = new String[outer.size()];
int i = 0;
for (List<String> inner : outer) {
result[i] = inner.toArray(String[]::new);
i++;
}

Related

How to traverse a List of Objects and merge specific value to one big list [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 1 year ago.
Improve this question
The title may sound confusing, but I think my problem is a lot simpler.
Here's what I have:
// a List containing `Boat` objects
private final List<Boat> placedBoats;
// each Boat contains a List<Coordinate> which represents a position on a grid
public List<Coordinate> getPosition() {
return positions;
}
Is there a way of how I can use the stream API to merge all List<Coordinate> into one big List<Coordinate>?
Yes. You can do it like this.
you stream the boats.
since each boat has a list of coordinates you must flatten those into a common stream
then collect the coordinates into a list.
List<Boat> placedBoats ...;
List<Coordinates> coordinates = placedBoats.stream()
.flatMap(boat->boat.getCoordinates().stream())
.toList(); // or .collect(Collectors.toList()) if pre java-16
Of course, by doing it as above, the source identity of where the coordinates came from (i.e. the individual boats) is lost.
Possible solution:
List<Coordinate> placedBoatCoordinates = new ArrayList<>();
for (Boat boat : placedBoats) {
placedBoatCoordinates.addAll(boat.getPosition());
}

How to get average in 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 2 years ago.
Improve this question
How to get average using functional programming in java?
This is what I tried ...
It seems like its not working at IntStream.of
I would like to get average from a specific row of the array
public static void average(List<List<String>> rows){
IntStream stream = IntStream.of(e -> Integer.parseInt(e.get(2)));
OptionalDouble obj = stream.average();
if (obj.isPresent()) {
System.out.println(obj.getAsDouble());
}
else {
System.out.println("-1");
}
}
rows is the array are rows read from an excel file.
Stream.of(elem1, elem2) creates a stream with the stated elements.
Imagine you have a box with 100 fotos in it.
If you do Stream.of(box), you get a stream of boxes, returning 1 box.
What you wanted was a stream of fotos. To get that, you want box.stream(), not Stream.of(box).
Your next problem then is that you don't seem to understand what reduce does. You need to tell the system how to integrate two results, not just how to get a result.
What you want here isn't reducing in the first place, you want to map a given 'foto' (a List of string in your case) to an integer, which requires not just e.get(), but also an Integer.parseInt, and you want map, not reduce.

How to stream the contents after Stream.Concat to avoid intermediate List [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 2 years ago.
Improve this question
I have two Lists A and B. I would like to merge them and stream again to form an Array.
I'm currently doing:
List<String> aggregate = Stream.concat(A.stream(), B.stream()).collect(Collectors.toList());
String[] final = aggregate.stream().limit(10).collect(Collectors.toList()).toArray(new String[10]);
Here, I'm having two intermediate lists that I'm just using to grab the final Array. Is there a way I can eliminate the two collect(Collectors.toList()) and write this in a single line?
Thank you
You don't need to collect at all you can directly use .toArray()
String[] res = Stream.concat(A.stream(), B.stream()).limit(10).toArray(String[]::new);
And if you want concat the stream and then get as array separately without collecting
Stream<String> aggregate = Stream.concat(A.stream(), B.stream());
String[] res = aggregate.limit(10).toArray(String[]::new);
Use this way
Stream.concat(A.stream(), B.stream()).collect(Collectors.toList());
This will return a list. If you want to be it an array, then do
Stream.concat(A.stream(), B.stream()).toArray(String[]::new);
for multiple streams we can do like
Stream.concat(firstStream, concat(secondStream, concat(thirdStream, fourthStream))).toArray(String[]::new);
I hope it helps

I need 2 denominational array sorted [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 5 years ago.
Improve this question
I am working on a project that has a list of student name and numbers, for example
James Bloggs,1
Paul Jonson,43
Andt Peters,23
Once I have them in an array I then need them sorted.
What is the best way of going about this. Its not the sort Im stuck on its the referencing the names to the numbers. I would have thought if I do a 2 denominational array only one would be sorted.
Any help would be great,
EDIT: I just realized this question was asking about a 2-dimensional array and my answer doesn't directly deal with that. I am skeptical that arrays should be involved at all. Arrays are usually for dealing with primitive data, and maybe if you are coming from a C background you'd think they'd be the natural thing to use. If you really honestly have to use arrays then this probably isn't the way to go.
https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
public void foo(){
// Use a TreeMap. It will sort keys on insertion.
Map<Integer,String> nameByNumber = new TreeMap<>();
nameByNumber.put(1, "James Boggs");
// etc. put all the entries in however you need to
List<Integer> sortedNumbers = personByNumber.getKeys();
List<String> namesSortedByNumber = personByNumber.getNames();
}
If you need it to be more organized and complex, you can encapsulate the name and number into a Class with a name and number property. Then you'd still use the number as the key, but you'd have the full class as the value. Do this if you need to have more than just a name, like last name, first name, address, etc.

Sort ArrayList data [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 6 years ago.
Improve this question
I'm preparing for an exam. I can read the CSV file but I don't know how to sort a data line.
For example, if "SchoolName.csv" has
Cayuga,Elkhart,Slocum,Westwood
Neches,Palestine,central
Dibolon
Lufkin,Holiday
After I sort the data the output should be
Dibolon // becuase it only contain one name.
Lufkin,Holiday
Neches,Palestine,central
Cayuga,Elkhart,Slocum,Westwood
So you want to sort based on number of elements. Assuming you have those elements in a Collection<String> csvlines:
csvlines.stream()
.sorted(Comparator.comparing(line -> StringUtils.countMatches(line, ",")))
.collect(Collectors.toList())
If you want to sort each row based on the number of names, you could do it like this
// Read the file's lines
List<String> lines = Files.readAllLines(pathToFile);
List<String> sortedLines = lines.stream().sorted(Comparator.comparing(line -> line.split(",").length)).collect(Collectors.toList());
Define a comparator, That is a class extending comparator and pass it as an argument to arraylistname.sort(comparator);
A comparator returns a negative integer, zero, or a positive integer if the first argument is less than, equal to, or greater than the second.
so
class CompareByLength implements Comparator {
compare(list a, list b) {
return a.size()-b.size();
}
}
alternatively use b.size()-a.size() if you want your list ordered the other way round.

Categories

Resources