How to put List elements to String Array in Java - java

Is there a way to put list elements to a String array in java? I sorted a Map by value using a custom Comparator and now trying to put the key(String) elements into an array. The only way I found is looping through the array and the sorted list at the same time and fill up the array that way but it only puts the last element into it.
Example:
My map without sorting: {a=5, b=2, c=8, d=1}
After sorted with custom Comparator: [c=8, a=5, b=2, d=1]
Now I simply need to put the key values (c,a etc.) to the tuple final String[] lettersWithBigValues = new String[n] where n is the length of the tuple.
However, after:
for (int i = 0; i < Integer.parseInt(args[1]); i++) {
System.out.println(lettersWithBigValues[i]+",");
}
The console gives back:
d,d,d,d given that the console line argument is 4
Here is the full function:
public String[] getTopLettersWithValues(final int n){
final String[] lettersWithBigValues = new String[n];
final Map<String, Integer> myMap = new HashMap<>();
int counter = 0;
for (final List<String> record : records) {
if (!myMap.containsKey(record.get(1))) {
myMap.put(record.get(1), counter += Integer.parseInt(record.get(4)));
} else {
myMap.computeIfPresent(record.get(1), (k,v) -> v + Integer.parseInt(record.get(4)));
}
}
System.out.println(myMap);
List<Map.Entry<String, Integer>> sorted = new LinkedList<>(myMap.entrySet());
// Sort list with list.sort(), using a custom Comparator
sorted.sort(valueComparator);
System.out.println(sorted);
for (int i = 0; i < lettersWithBigValues.length; i++) {
for (Map.Entry<String, Integer> values: sorted) {
lettersWithBigValues[i] = values.getKey();
}
}
return lettersWithBigValues;
}
Where records is a List of data read from a csv file.
And here is the comparator:
public Comparator<Map.Entry<String, Integer>> valueComparator = (o1, o2) -> {
Integer v1 = o1.getValue();
Integer v2 = o2.getValue();
return v2.compareTo(v1);
};

You can attain the array of keys as follows:
String [] lettersWithBigValues = myMap.entrySet().stream() // entries of your intial map
.sorted(valueComparator) // sorted by your comparator
.map(Map.Entry::getKey) // mapped to only the key e.g. 'd', 'a'
.toArray(String[]::new); // converted to array

Seems to me that you have mistakenly used a nested for loop, you just need the one:
for (int i = 0; i < lettersWithBigValues.length; i++) {
lettersWithBigValues[i] = sorted.get(i).getKey();
}
That would return the array: c, a, b, d

As an added suggestion you could also have created the Comparator using the Entry.comparingByValue() method.
Comparator<Entry<String,Integer>> valueComparator =
Entry.<String,Integer>comparingByValue().reversed();
It returns a ready made Comparator that compares by the natural order of the value. So to sort in reverse, you just need to tag on the reversed() method which is defined in the Comparator interface.

Related

Java ArrayList sort two lists in same order

I have two ArrayLists in Java. Both lists are unsorted.
ArrayList<Integer> listOne = new ArrayList<>();
listOne.add(2);
listOne.add(1);
listOne.add(4);
listOne.add(8);
listOne.add(6);
ArrayList<String> listTwo = new ArrayList<>();
listTwo.add("ant");
listTwo.add("bear");
listTwo.add("cat");
listTwo.add("dog");
listTwo.add("zebra");
I want to sort listOne in natural order and each item of listTwo should be sorted according to the position in listOne:
What I have so far is:
Collections.sort(listOne);
for (int i = 0; i < listOne.size(); i++) {
int intTest = listOne.get(i);
String stringTest = listTwo.get(i);
System.out.println(intTest);
System.out.println(stringTest);
}
This prints :
1 ant, 2 bear, 4 cat , 6 dog , 8 zebra
My expected print output is:
1 bear, 2 ant, 4 cat, 6 zebra, 8 dog
So that when the item of listOne "1", that changed the position from 2nd to 1st, the item "bear" in listTwo, that was on the 2nd position, should also print on the 1st position.
What would be the most simple and efficient way to do this?
Create an ordered list of indices:
int n = listOne.size();
assert n == listTwo.size();
Integer[] indices = new Integer[n];
for (int i = 0; i < n; ++i) {
indices[i] = i;
}
Sort that list using a comparator that compares indices by looking at the corresponding elements in listOne.
Arrays.sort(
indices,
new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return listOne.get(a).compareTo(listOne.get(b));
}
});
Now you can use indices to reorder both lists:
static <T> void reorder(Integer[] indices, List<T> mutatedInPlace) {
List<T> tempSpace = new ArrayList<T>(indices.length);
for (int index : indices) {
tempSpace.add(mutatedInPlace.get(index);
}
mutatedInPlace.clear();
mutatedInPlace.addAll(tempSpace);
}
reorder(indices, listOne);
reorder(indices, listTwo);
TreeMap best suits this situation. It inserts the data in sorted order so basically store the key and against each key you can store the animal.
Map<Integer,String> sortedMap = new TreeMap<Integer,String>();
sortedMap.push(listOne.get(i),listTwo.get(listOne.get(i)));
In case you want to stick to ArrayList, you can iterate over the listOne and push it in HashMap<Integer,String>
iterate over list (for example i)
map.put( listOne.get(i), secondList.get(i));
So the hashMap would be like (2, "ant");
Collections.sort(listOne);
Against each entry, you can get the corresponding animal from map
We can use HashMap data structure, It contains “key-value” pairs and allows retrieving the value by key.
int i = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Here we’re storing the items from listOne as keys and their position as a value in the HashMap.
for (Integer num : listOne) {
map.put(num, i);
i++;
}
We’re printing the elements from listTwo as per the items from the listOne changed their position.
Collections.sort(listOne);
for (Integer num : listOne) {
System.out.println(num + " " + listTwo.get(map.get(num)));
}
One Solution:
int i = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer num : listOne) {
map.put(num, i);
i++;
}
Collections.sort(listOne);
for (Integer num : listOne) {
System.out.println(num + " " + listTwo.get(map.get(num)));
}
Output is:
1 bear,
2 ant,
4 cat,
6 zebra,
8 dog
If you use a Map<Integer, String> for this, you don't even need to sort it if you take the TreeMap implementation.
It basically works as follows:
public class StackoverflowMain {
public static void main(String[] args) {
// initialize a map that takes numbers and relates Strings to the numbers
Map<Integer, String> animals = new TreeMap<Integer, String>();
// enter ("put" into the map) the values of your choice
animals.put(2, "ant");
animals.put(1, "bear");
animals.put(4, "cat");
animals.put(8, "dog");
animals.put(6, "zebra");
// print the whole map using a Java 8 forEach statement
animals.forEach((index, name) -> System.out.println(index + ": " + name));
}
}
This code will output
1: bear
2: ant
4: cat
6: zebra
8: dog
Putting the suggestions of all the friendly and helpful people together (plus some other research and test), here is the final code I came up with:
ArrayList<String> listOne = new ArrayList<>();
listOne.add("one");
listOne.add("eight");
listOne.add("three");
listOne.add("four");
listOne.add("two");
ArrayList<String> listTwo = new ArrayList<>();
listTwo.add("ant");
listTwo.add("bear");
listTwo.add("cat");
listTwo.add("dog");
listTwo.add("zebra");
Map<String, String> sortedMap = new TreeMap<String, String>();
for (int i = 0; i < listOne.size(); i++) {
String stringkey = listOne.get(i);
String stringValue = listTwo.get(i);
sortedMap.put(stringkey, stringValue);
}
print output = {eight=bear, four=dog, one=ant, three=cat, two=zebra}

How to Output the Reverse of a Map [Java]

The problem goes as follows: Jane has friends who she associates a number with. I must output the friends from the least amount of likes to the most likes.
My main curiosity is how can I reverse the order of the map values when outputting.
In my code I had to extract the values through an Iterator (I was unable to use a Collection directly) and then store each String into an ArrayList by inserting each consecutive element at index 0. This, as a result, reversed the order which worked I suppose.
import java.util.*;
import java.io.*;
import static java.lang.System.*;
public class Friends {
public static void main(String args[]) throws IOException
{
Scanner line = new Scanner(new File("friends.dat"));
int trials = line.nextInt();
for(int k = 0 ; k < trials ; k++)
{
TreeMap<Integer, String> m = new TreeMap<Integer,String>();
int subtrials = line.nextInt();
for(int a = 0; a < subtrials ; a++)
{
String name = line.next();
int likes = line.nextInt();
m.put(likes,name);
}
Iterator iter = m.values().iterator(); //**Code of interest starts here**
ArrayList<String> list = new ArrayList<String>();
while(iter.hasNext()) {
list.add(0, (String)iter.next());
}
for(int a = 0 ; a < list.size() ; a++)
{
if(a == list.size() - 1)
out.print(list.get(a));
else
out.print(list.get(a) + ", ");
}
out.println();
}
}
}
You can use a custom comparator to reverse the order of entries in the map (note that this only applies to TreeMap - other map implementations don't care about ordering).
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>((key1, key2) -> Integer.compare(key2, key1)); //Custom comparator.
map.put(1, "Bob");
map.put(3, "Baz");
map.put(2, "Foo");
System.out.println(map);
}
Using the number of likes as a key seems strange, as multiple friends might have the same number of likes.
In Java 8, I'd do the following:
Map<String, Integer> map = new HashMap<>();
map.put("Jack", 7);
map.put("Jill", 3);
map.put("John", 12);
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue((a, b) -> b.compareTo(a)))
.forEach(System.out::println);
Essentially, this turns the map entries into a stream, compares them by value using a comparator that reverses the natural order, and then prints out every entry.
Which results in:
John=12
Jack=7
Jill=3
Please try this:
m.forEach((a,b)->System.out.print(b+", "));
This will give you a sorted map, from the least amount of likes to the most likes.
If you want a sorted map from the most likes to the least amount of likes, you can do this:
TreeMap<Integer, String> m = new TreeMap<Integer,String>(Collections.reverseOrder());
You could simply reverse your list.
list.reverse();
Alternately, you could use the TreeMap constructor with a reverse comparator, to store the map in descending order.
... = new TreeMap<>(Collections.reverseOrder(Integer::compare));

Find most appearing string in ArrayList

If I have an ArrayList of these strings...
"String1, String1, String1, String2, String2, String2, String3, String3"
How can I find the most appearing string in this list? If there are any duplicates, I would want to put both into the same list and deal with that accordingly. How could I do this, assuming that the list of strings could be of any size.
This is about as far as I've gotten:
public String getVotedMap() {
int[] votedMaps = new int[getAvailibleMaps().size()];
ArrayList<String> mostVoted = new ArrayList<String>();
int best = 0;
for(int i = 0; i < votedMaps.length; i++) {
if(best > i) {
best = i;
} else if(best == i) {
} else {
}
}
}
getAvailibleMaps() is a list of Maps that I would choose from (again, can get any size)
Thanks!
Use HashMap
The basic Idea is loading all the values into a hashtable. Hash tables are nice because you can assign a value to a unique key. As we add all the keys to the hashtable we are checking to see if it already exists. If it does then we increment the value inside.
After we have inserted all the elements into the hashtable then we go through the hashtable one by one and find the string with the largest value. This whole process is O(n)
Map<String, Integer> map = new HashMap<String, Integer>();
for(int i = 0; i < array.length(); i++){
if(map.get(array[i]) == null){
map.put(array[i],1);
}else{
map.put(array[i], map.get(array[i]) + 1);
}
}
int largest = 0;
String stringOfLargest;
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
if( value > largest){
largest = value;
stringOfLargest = key;
}
}
if you want multiple largest strings then instead of just finding the largest and being done. You can add all the largest to a mutable list.
for example:
int largest = 0;
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
if( value > largest){
largest = value;
}
}
ArrayList<Object> arr = new ArrayList<Object>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
if( value == largest){
arr.add(key);
}
}
arr now stores all the most frequently appearing strings.
This process is still O(n)
Just iterate through the list and keep a HashMap<String,Integer> that counts how many times the string has appeared, eg.
Map<String,Integer> counts = new HashMap<String,Integer>();
for(String s : mostVoted) {
if(counts.containsKey(s)) {
counts.put(s,counts.get(s)+1);
} else {
counts.put(s,1);
}
}
// get the biggest element from the list
Map.Entry<String,Integer> e = Collections.max(counts.entrySet(),new Comparator<Map.Entry<String,Integer>>() {
#Override
public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
System.out.printf("%s appeared most frequently, %d times%n",e.getKey(),e.getValue());
If you can use java 8, this will give you a list of most frequent strings or throw an exception if the list is empty.
List<String> winners = strings.stream()
.collect(groupingBy(x->x, counting())) // make a map of string to count
.entrySet().stream()
.collect(groupingBy( // make it into a sorted map
Map.Entry::getValue, // of count to list of strings
TreeMap::new,
mapping(Map.Entry::getKey, toList()))
).lastEntry().getValue();

Map elements in a list to positions in another list

Imagine we have two lists and want to know the postions of elements from one list in the other. To illustrate:
List<String> one = Arrays.asList("B", "I", "G");
List<String> another = Arrays.asList("L", "A", "R", "G", "E");
Result would be:
[-1, -1, 3]
because neither B nor I occur in second list, but G does on 3rd position.
This is what I came with so far:
<E> List<Integer> indices(List<E> elements, List<E> container) {
List<Integer> indices = new ArrayList<>(elements.size());
for (int i = 0; i < elements.size(); i++) {
indices.add(container.indexOf(indices.get(i)));
}
return indices;
}
Is there a faster solution that avoids internal loop in List.indexOf()?
You can use Map:
Map<String, Integer> otherMap = new HashMap<>(other.size());
int index = 0;
for(String otherElem : other) {
otherMap.put(otherElem, index++);
}
And then:
for(String oneElem : one) {
Integer index = otherMap.get(oneElem);
indices.add(index == null ? -1 : index);
}
Doing so, you get the index directly instead of iterating on a potentially very big list each time you look for and index.
You can use a HashMap<String, Integer> that would map every character to its position. Then use HashMap method .containsKey() to find out, if a certain String is present in the field and .get() to find out the position.
HashMap<String, Integer> another;
for (String str : one) {
if (another.contains(str)) {
result.add(another.get(str));
} else {
result.add(-1);
}
}

Syncronized sorting between two ArrayLists

I have two ArrayLists.
The first contains a group of words with capitalization and
punctuation.
The other contains this same group of words, but with the
capitalization and punctuation removed.
.
ArrayList1 ..... ArrayList2
MURDER! ........ murder
It's ........... its
Hello .......... hello
Yes-Man ........ yesman
ON ............. on
The second array has all the words alphabetized and all the letters in each word alphabetized. It looks something like this:
aemnsy
demrru
ehllo
ist
no
I want to make it so that when I arrange the words in ArrayList two into alphabetical order, all the words from ArrayList one follow suite:
ArrayList1 ..... ArrayList2
Yes-Man ........ aemnsy
MURDER! ........ demrru
Hello .......... ehllo
It's ........... ist
ON ............. no
I tried to make a loop with a for statement or two, but it ended up not working and became very long. How do I do this? How do I do this efficiently?
Here is a function to sort multiple lists based on a single 'key' list. The lists do not need to be the same type, here the key list is type String and it's used to sort a String, Integer, and Double list (Ideone Example):
List<String> key = Arrays.asList("demrru", "ist", "ehllo", "aemnsy", "no");
List<String> list1 = Arrays.asList("MURDER!","It's", "Hello","Yes-Man", "ON");
List<Integer> list2 = Arrays.asList(2, 4, 3, 1, 5); // Also use Integer type
List<Double> list3 = Arrays.asList(0.2, 0.4, 0.3, 0.1, 0.5); // or Double type
// Sort all lists (excluding the key)
keySort(key, list1, list2, list3);
// Sort all lists (including the key)
keySort(key, key, list1, list2, list3);
Output:
// Sorted by key:
[Yes-Man, MURDER!, Hello, It's, ON]
[aemnsy, demrru, ehllo, ist, no]
[1, 2, 3, 4, 5]
[0.1, 0.2, 0.3, 0.4, 0.5]
Sort Function
An Ideone Example can be found here which includes validation of parameters and a test case.
public static <T extends Comparable<T>> void keySort(
final List<T> key, List<?>... lists){
// Create a List of indices
List<Integer> indices = new ArrayList<Integer>();
for(int i = 0; i < key.size(); i++)
indices.add(i);
// Sort the indices list based on the key
Collections.sort(indices, new Comparator<Integer>(){
#Override public int compare(Integer i, Integer j) {
return key.get(i).compareTo(key.get(j));
}
});
// Create a mapping that allows sorting of the List by N swaps.
Map<Integer,Integer> swapMap = new HashMap<Integer, Integer>(indices.size());
// Only swaps can be used b/c we cannot create a new List of type <?>
for(int i = 0; i < indices.size(); i++){
int k = indices.get(i);
while(swapMap.containsKey(k))
k = swapMap.get(k);
swapMap.put(i, k);
}
// for each list, swap elements to sort according to key list
for(Map.Entry<Integer, Integer> e : swapMap.entrySet())
for(List<?> list : lists)
Collections.swap(list, e.getKey(), e.getValue());
}
First Way - I use map whose key is from arrayList2 and value is from arrayList1. Putting data to map is up to you. After sorting arrayList2, I get its value from map.
List<String> arrList1 = new ArrayList<String>();
arrList1.add("MURDER!");
arrList1.add("It's");
arrList1.add("Hello");
arrList1.add("Yes-Man");
arrList1.add("ON");
List<String> arrList2 = new ArrayList<String>();
arrList2.add("demrru");
arrList2.add("aemnsy");
arrList2.add("ist");
arrList2.add("ehllo");
arrList2.add("no");
Map<String, String> map1 = new HashMap<String, String>();
map1.put("aemnsy", "Yes-Man");
map1.put("demrru", "MURDER!");
map1.put("ehllo", "Hello");
map1.put("ist", "It's");
map1.put("no", "ON");
Collections.sort(arrList2);
for (String s : arrList2){
System.out.println(s + "..........." + map1.get(s));
}
Second Way - Another way is you can use only TreeMap which is already sorted instead of two ArrayList.
Map<String, String> map2 = new TreeMap<String, String>();
map2.put("ehllo", "Hello");
map2.put("aemnsy", "Yes-Man");
map2.put("demrru", "MURDER!");
map2.put("no", "ON");
map2.put("ist", "It's");
for (Map.Entry<String, String> entry : map2.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
Third way - only using 2 ArrayList, but we have to write sorting method by our own. Have you notice that your 2 ArrayList elements such as aemnsy from arrayList2 and Yes-Man from arrayList1 have same index? I use that point.
selectionSort1(arrList2, arrList1);
for(int i = 0; i < arrList1.size(); i++){
System.out.println(arrList2.get(i) + "---" + arrList1.get(i));
}
public static void selectionSort1(List<String> x, List<String> y) {
for (int i=0; i<x.size()-1; i++) {
for (int j=i+1; j<x.size(); j++) {
if (x.get(i).compareTo(x.get(j)) > 0) {
//... Exchange elements in first array
String temp = x.get(i);
x.set(i, x.get(j));
x.set(j, temp);
//... Exchange elements in second array
temp = y.get(i);
y.set(i, y.get(j));
y.set(j, temp);
}
}
}
}
A Quick Answer.
public class MapAlph {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
String txt = "Murde!r!";
ArrayList<Character> alph = new ArrayList<Character>();
for (int i = 0; i < txt.length(); i++)
if (Character.isLetter(txt.charAt(i)))
alph.add(txt.charAt(i));
Collections.sort(alph);
Collections.reverse(alph);
String val = "";
for (Character c : alph)
val += c;
map.put(txt, val);
System.out.print(txt + " ........ " + map.get(txt));
}
}
You can make use of TreeMap, if you wish.
Map<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.put("demrru", "MURDER!");
sortedMap.put("ist", "It's");
sortedMap.put("aemnsy", "Yes-Man");
sortedMap.put("ehllo", "Hello");
sortedMap.put("no", "ON");
You can try this:
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class SortService {
public static void main(String[] args) {
Map<String, String> originalMap = new HashMap<String, String>();
originalMap.put("aemnsy", "Yes-Man");
originalMap.put("demrru", "MURDER!");
originalMap.put("ehllo", "Hello");
originalMap.put("ist", "It's");
originalMap.put("no", "ON");
Map<String, String> sortedMap = new TreeMap<String, String>(originalMap);
System.out.println(sortedMap);
}
}
output:
{aemnsy=Yes-Man, demrru=MURDER!, ehllo=Hello, ist=It's, no=ON}

Categories

Resources