Sort ArrayList data [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 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.

Related

Convert List<List<String>> to String[][] [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 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++;
}

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 add different values to an arraylist? [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 4 years ago.
Improve this question
I have a method that randomly selects objects from an arraylist. Those objects are being added to another arraylist I created. How can I make it so that the same object is not added twice?
Let's say I have an arraylist:
["Chicken", "Dinner", "Noodles"]
I have another arraylist that I want to add values randomly from the first arraylist:
[]
So I use:
Math.random to get values from 0-2 and add them to the new arraylist.
Let's name the empty one list2 and the top one firstlist
So:
Assuming integer i is a random number 0-2.
list2.add(firstlist.get(i));
Yet this has a chance to add the same value, how can I check through list2, to make sure it hasn't been added yet, so I can not add it and pick another value?
Replace the other list with a java.util.Set. If your objects have correct hashCode() and equals() then they won't be added twice. In other words, use the right collection type for the job.

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.

What happens when an integer element in a list is changed to string 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 8 years ago.
Improve this question
I have an array list. In that list I have a couple of string elements and few integer elements. I need to change all the elements in my arraylist to string so that I can modify the string elements. So, when I am doing this, even the integer elements in my arraylist are being changed to string. Would that be a problem if tried to access the integer elements after they are changed to string?
It is possible to use parseInt() so no it is not a problem. You can read more here: http://www.tutorialspoint.com/java/number_parseint.htm
You shouldn't attempt to alter the types of elements contained in a list. Instead, create a new list of strings, and add to it appropriately:
List<String> strings = new ArrayList<>(integers.size());
for (Integer a : integers)
strings.add(a.toString());

Categories

Resources