Skip to content

Instantly share code, notes, and snippets.

@ababup1192
Created April 6, 2017 07:04
Show Gist options
  • Save ababup1192/8283cae04ddbcf9bd19789b7a0201365 to your computer and use it in GitHub Desktop.
Save ababup1192/8283cae04ddbcf9bd19789b7a0201365 to your computer and use it in GitHub Desktop.
fuck code.
import java.util.Map;
import java.util.HashMap;
public class Main {
private Map<String, String> map;
public Main() {
Map<String, String> map = new HashMap<String, String>();
map.put("a", "123");
map.put("b", "d");
map.put("c", "456");
System.out.println(getValueAsInt("a"));
System.out.println(getValueAsInt("b"));
System.out.println(getValueAsInt("c"));
}
public int getValueAsInt(String key) {
if(map.get(key) == null){
return -1;
} else {
int res;
try{
res = Integer.parseInt(map.get(key));
} catch(NumberFormatException e) {
e.printStackTrace();
res = -1;
}
return res;
}
}
public static void main(String args[]){
new Main();
}
}
@hishidama
Copy link

hishidama commented Apr 6, 2017

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class Java9 {
	private final Map<String, Integer> map = Map.of("a", "123", "b", "d", "c", "456")
			.entrySet().stream()
			.collect(Collectors.toMap(Map.Entry::getKey, entry -> {
				try {
					return Integer.parseInt(entry.getValue());
				} catch (NumberFormatException e) {
					return -1;
				}
			}));

	public int getValueAsInt(String key) {
		return map.getOrDefault(key, -1);
	}

	public static void main(String... args) {
		new Java9().print(args);
	}

	private void print(String... keys) {
		Arrays.stream(keys).forEach(key -> System.out.println(getValueAsInt(key)));
	}
}

@hishidama
Copy link

hishidama commented Apr 6, 2017

import java.util.Arrays;
import java.util.Map;

// https://gist.github.com/gakuzzzz/9f35617943decf2893ea
import static jp.t2v.lab.syntax.MapStreamSyntax.entryToMap;
import static jp.t2v.lab.syntax.MapStreamSyntax.values;

public class Java9 {
	private final Map<String, Integer> map = Map.of("a", "123", "b", "d", "c", "456")
			.entrySet().stream()
			.map(values(s -> {
				try {
					return Integer.parseInt(s);
				} catch (NumberFormatException e) {
					return -1;
				}
			})).collect(entryToMap());

	public int getValueAsInt(String key) {
		return map.getOrDefault(key, -1);
	}

	public static void main(String... args) {
		new Java9().print(args);
	}

	private void print(String... keys) {
//		Arrays.stream(keys).forEach(key -> System.out.println(getValueAsInt(key)));
		Arrays.stream(keys).mapToInt(this::getValueAsInt).forEach(System.out::println);
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment