Lexicographic sorting in java? - java

I am trying to sort 3 strings alphabetically using the compareTo method in java without using arrays.
Is the fastest way to do this by setting up 6 compare statements and sorting by least to greatest or is there any easier way? Thanks!

put it into TreeSet.
TreeSet<String> t = new TreeSet<>();
t.add("stack");
t.add("over");
t.add("flow");
System.out.println(t);
OutPut:
[flow, over, stack]

Related

easiest and fastest way to sort an arraylist containing strings like "0.222:Hello test" by its float?

im trying for a few days now to sort an arraylist which consist out of these
strings(by its float at the beginning of the list):
"0.1:test1"
"0.11:test2"
"0.21:test3"
"0.14:test4"
"2.1:test5"
i wasn't able to find a way, the closest attempt was with collections.sort
but it only sorted the list by its first number which isn't what im looking for:/
could someone help me out? thanks a lot in advance, this site has helped me a lot with my java hobby projects already:)
Collections.sort(arrayList1);
Collections.reverse(arrayList1);
for (String value : arrayList1){
System.out.println(value);
}
sorted by first number not by full number
Easiest solution:
List<String> list = Arrays.asList("0.1:test1", "0.11:test2", "0.21:test3", "0.14:test4", "2.1:test5");
list.sort(Comparator.comparingDouble(s -> Double.parseDouble(s.split(":", 2)[0])));
System.out.println(list);
Output
[0.1:test1, 0.11:test2, 0.14:test4, 0.21:test3, 2.1:test5]
With the split and the parseDouble calls inside the compare method, it is certainly not the fastest solution, but it is the easiest.

Sort integers having special character in Java

I have a problem where I need to sort Integers separated by hyphen either in ascending or descending order.
I tried using
Collections.sort(list, Collections.reverseOrder());
Where list is an instance of ArrayList created, but its not giving me the exact result.
The arrayList looks like this:
[91,95,96-1,94-2,94-1,100-2].
The expected way is:
[91,94-1,94-2,95,96-1,100-2]
Using the default sorting on Strings will use a lexicographical order, whereas you intend to sort the Strings in a numerical order (and if the first number is equal, by the second number). A way to accomplish this is by using two Comparators:
List<String> list = new ArrayList<>(Arrays.asList("96-1","91","94-2","100-2","94-1","95"));
System.out.println("Unsorted: "+list);
Comparator<String> primaryComparator =
(a,b)->Integer.valueOf(a.split("-")[0])
.compareTo(Integer.valueOf(b.split("-")[0]));
Comparator<String> secondaryComparator =
(a,b)->Integer.valueOf(a.split("-")[1])
.compareTo(Integer.valueOf(b.split("-")[1]));
list.sort(primaryComparator.thenComparing(secondaryComparator));
System.out.println("Sorted: "+list);
list.sort(primaryComparator.thenComparing(secondaryComparator).reversed());
System.out.println("Sorted in reverse: "+list);
Try it online.
As for the comparators themselves, I assumed the Strings in the list are always valid, and always of the form \d+(-\d+)?, so either an integer, or two integers separated with a hyphen. (If this is not the case, you might want to add some additional checks/validations with a custom Java 7 style comparator to make it more readable then the Java 8 style lambdas.)
The .split("-")[0] / .split("-")[1] will split this String on the hyphen, and takes either the first or last integer depending on the comparator. It will then convert this to an integer with Integer.valueOf(...), and will use the default integer comparing builtin Integer1.compareTo(Integer2).

How to delete similar elements from String array or ArrayList [duplicate]

This question already has answers here:
How to get unique values from array
(13 answers)
Closed 7 years ago.
I'm totally new to programming and I have String array:
String dates[] = {"01-01-1993", "19-11-1993", "01-01-1993", "03-03-2000", "03-03-2000"};
In the above array dates[0] == dates[2] and dates[3] == dates[4], I want to delete the duplicate values which IS REPEATED and I want program to produce result like this:
dates[] = {"01-01-1993", "19-11-1993", "03-03-2000"}
Some are using ArrayList concept some are using complex for loops and I'm confused, so could you please help in achieving the above task.
Thanks In Advance.
You can use a Set to remove duplicates.
Set<T> dateSet = new HashSet<T>(Arrays.asList(dates));
dateSet will only contain unique values.
If you need to get back to an array
dates = dateSet.toArray(new String[dateSet.size()]);
Your question raises a few points:
In general, this kind of manipulation of collections is much easier and cleaner if you use the Collection classes (Set, List, etc). For example, a Set guarantees uniqueness of the elements:
String dates[] = {"01-01-1993", "19-11-1993","01-01-1993","03-03-2000","03-03-2000"};
Set<String> uniqueDates = new HashSet<>(Arrays.asList(dates));
But HashSet is unordered; if you iterate over uniqueDates the order in which you get the back is arbitrary. If the order is important, you could use LinkedHashSet:
Set<String> orderedUniqueDates = new LinkedHashSet<>(Arrays.asList(dates));
The basic collection that come with Java are pretty good; but if you use Google's Guava library (https://github.com/google/guava), it gets really nice and you can do really powerful things like finding intersections of sets, set differences etc.:
Set<String> uniqueDates = Sets.newHashSet(dates);
More fundamentally, String is a very poor choice of data type to represent Dates. Consider using either java.util.Date or (if using a Java version prior to 8) org.joda.time.DateTime (http://www.joda.org/joda-time/). Not only will this give you type safety and ensure that your data is really all dates, but you could then do things like sorting.
Using Java 8 you can do the following:
String dates[] = {"01-01-1993", "19-11-1993", "01-01-1993", "03-03-2000", "03-03-2000"};
dates = Arrays.stream(dates).distinct().toArray(String[]::new);
this will work simply
Set<T> tempSet= new HashSet<T>(Arrays.asList(dates));
String[] dates= tempSet.toArray(new String[tempSet.size()]);//copy distinct values

Comparing equals between 1D and 2D array in java

I have two questions:
I am using JAVA programming language and I have found some difficulties using Arrays.
Here are some different arrays :
Object [] play1 = {0,3,6};
Object [] play2 = {0,3,6,4};
Object[][] pre = {{0,1,2},{0,3,6},{2,5,8},{6,7,8},{0,4,8},{2,4,6}};
Question 1 : Is it possible to check equals between play1 and pre using deepEquals? I also know that pre is 2D array and play1 is 1D array.
If I want to check whether play1 is equal to pre, then I might check like:
if(Arrays.deepEquals(pre, play1)){
System.out.print("true");
}else{System.out.print("false");}
Is the code correct? Even though is is possible to check equals between 1D and 2D arrays? Or do I have to use ArrayList? I am not that much familiar with ArrayList. Would appreciate if anyone explain with example.
Question 2 : However, if I want to check between play1 and play2, then also the output is false. I want to check between two arrays even though they don't have equal element but if both array consists the same element such as: {0,3,6} can be found in both play1 and play2, then the output must come true..
Thanks.
For Question2:
You can create List of objects and check as follows:
List<Object> play1List = Arrays.asList(play1);
List<Object> play2List = Arrays.asList(play2);
if(play1List.containsAll(play2List) || play2List.containsAll(play1List))
System.out.println("founD");
For Question1:
List<Object> play1List = Arrays.asList(play1);
for (int i =0 ; i< pre.length;i++){
List<Object> preList = Arrays.asList(pre[i]);
if(preList.equals(play1List)){
System.out.println("FounD"+preList);
break;
}
}
From the API docs:
Two array references are considered deeply equal if both are null, or
if they refer to arrays that contain the same number of elements and
all corresponding pairs of elements in the two arrays are deeply
equal.
From your question I understand that you are searching for a subgroup of the array.
I don't think that there's a function for that on the JDK, probably you have to develop your own function iterating the arrays.

Sorting a collection of songs by runtime

I have to make a program that sorts a collection of songs by runtime. I have to analyse a selection of songs, each with a "Title" string, a "Composer" string, and a "Running Time" integer. Input will be piped through stdin, and output will be in stdout.
Here's an example input:
3
&
Pink Frost&Phillipps, Martin&234933
Se quel guerrier io fossi&Puccini, Giacomo&297539
Non piu andrai&Mozart&234933
M'appari tutt'amor&Flotow, F&252905
And output:
Se quel guerrier io fossi&Puccini, Giacomo&297539
M'appari tutt'amor&Flotow, F&252905
Non piu andrai&Mozart&234933
I know I have to sort these by Running Time, but I'm not sure which sorting algorithm to use. By general knowledge, the two sorting algo's that come to mind are Merge Sort and Quicksort, because they seem to be the quickest on average. I also have the idea of using a Comparator to compare two "Running time" elements in a Collection.
Could someone please point me in the right direction?
The easiest way is to write a class to hold the above values, which implements Comparable interface (or you could write up your own Comparator). The compareTo method can check the runtime and return a value accordingly.
Then pass it up to Collections.sort() method. This method uses a optimized version of Merge Sort. You don't have to write your own sorting logic to handle it this way, and you can rely on the Java Platform to do it for you. Unless you need specific performance tuning of sorting method, I guess this is the simplest way to go (KISS - Keep It Simple, Stupid).
Excerpt from Java API Docs on Collections.sort (http://download.oracle.com/javase/1,5.0/docs/api/java/util/Collections.html#sort%28java.util.List%29):
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.
Just stick to compareTo() method for String or int (running tittle) and use them in your Comparators. Nextly - use Collections.sort() which uses merge sort that is quite good :)
Ah and during runtime you should add those songs to list of songs - ArrayList or LinkedList. And sort them by Collections.sort(yourListName, new yourComparatorName());

Categories